ruby on rails best_in_place nomethoderror - ruby-on-rails

i am getting an error with the best_in_place gem.
i want to edit my comments inside of the post show action since i render all comments there.
NoMethodError in Posts#show
Showing undefined method `erererer' for #<Comment:0x00007fc0ff1721c8>
comment view that i render in posts show page.
<!--<h3>there are <%#= pluralize(#comments.count, "comment") %></h3> -->
<% #comments.each do |comment| %>
<div class="media mb-5 ">
<% if comment.user.avatar.present? %>
<%= image_tag comment.user.avatar.url, class: 'rounded mr-3 d-flex', width: 42, height: 42%>
<% else %>
<%= random_avatar 42, "d-flex rounded mr-3"%>
<% end %>
<div class="media-body">
<div class="d-flex justify-content-between" />
<h5 class="mt-0"><a><%=link_to comment.user.username, user_path(comment.user) %></a></h5>
<p class="m-0 form-group">created at <%=time_ago_in_words(comment.created_at) %></p>
</div>
<%= best_in_place comment, comment.body, :as => :textarea %>
<% if current_user == comment.user %>
<span style="font-size: 15px;">
<%= link_to '', [comment.post, comment], method: :delete, data: {confirm: "sure?"}, class: ' btn btn-outline-danger btn-sm pull-right fa fa-trash-o' %>
<%= link_to '',edit_post_comment_path(comment.post, comment), class: 'btn btn-outline-warning btn-sm pull-right fa fa-pencil-square-o' %>
</span>
<% end %>
</div>
</div>
</section>
<%end%>
application.js
$(document).ready(function() {
/* Activating Best In Place */
$('.best_in_place').best_in_place();
});
comments_controller.rb
def update
if #comment.update(params[:comment].permit(:body))
format.html { redirect_to post_path(#post) }
format.json { head :ok }
else
format.html { render :action => "edit" }
format.json { respond_with_bip(#comment) }
end
end
comment.rb
class Comment < ApplicationRecord
belongs_to :post
belongs_to :user
validates :body, presence: true
end
post.rb
class Post < ApplicationRecord
belongs_to :user
has_many :comments, dependent: :destroy
validates :title, presence: true, length: { minimum: 5 }
validates :body, presence: true, length: { minimum: 240 }
post.controller - add post controller code to question
class PostsController < ApplicationController
before_action :find_post, only: %i[destroy edit update comment_owner upvote downvote]
after_action :verify_authorized, only: [:edit, :update, :destroy, :create, :new]
layout '_app_nav'
def index
return redirect_to post_path(params[:post_id]) if params[:post_id]
return redirect_to user_path(params[:user_id]) if params[:user_id]
#post = Post.all.order('created_at DESC')
#posts = Post.all.order('created_at DESC')
#user = User.all
#posts = if params[:search]
else
Post.all.order('created_at DESC')
end
#comments = Comment.all
end
def new
#post = Post.new
end
def create
#post = current_user.posts.build(post_params)
authorize #post
if #post.save!
redirect_to #post
else
render 'new'
end
end
def show
#post = Post.find(params[:id])
#user = #post.user
#comments = Comment.where(post_id: #post).order('created_at DESC').paginate(:page => params[:page], :per_page => 5)
end
def edit
authorize #post
end
def update
authorize #post
if #post.update(post_params)
redirect_to #post, notice: 'updated.'
else
render :edit
end
end
end
def destroy
#post = Post.find(params[:id])
authorize #post
#post.destroy
redirect_to posts_path
end
private
def post_params
params.require(:post).permit(:title, :body, :user_id)
end
def find_post
#post = Post.find(params[:id])
end
UPDATE
This is the entire request that i get when trying to open posts#show
Started GET "/news/2" for 127.0.0.1 at 2018-07-30 03:12:49 +0200
(0.6ms) SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
Processing by PostsController#show as HTML
Parameters: {"id"=>"2"}
Post Load (0.4ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = $1 LIMIT $2 [["id", 2], ["LIMIT", 1]]
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 3], ["LIMIT", 1]]
Rendering posts/show.html.erb within layouts/_app_nav
Rendered comments/_form.html.erb (27.1ms)
Comment Load (0.9ms) SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = 2 ORDER BY created_at DESC LIMIT $1 OFFSET $2 [["LIMIT", 5], ["OFFSET", 0]]
CACHE User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 3], ["LIMIT", 1]]
Rendered comments/_comment.html.erb (14.2ms)
Rendered posts/show.html.erb within layouts/_app_nav (442.2ms)
Completed 500 Internal Server Error in 509ms (ActiveRecord: 12.4ms)
ActionView::Template::Error (undefined method `erererer' for #<Comment:0x00007feba5717bc0>):
15:
16: <p class="m-0 form-group">created at <%=time_ago_in_words(comment.created_at) %></p>
17: </div>
18: <%= best_in_place comment, comment.body, :as => :textarea %>
19: <% if current_user == comment.user %>
20: <span style="font-size: 15px;">
21: <%= link_to '', [comment.post, comment], method: :delete, data: {confirm: "sure?"}, class: ' btn btn-outline-danger btn-sm pull-right fa fa-trash-o' %>
app/views/comments/_comment.html.erb:18:in `block in _app_views_comments__comment_html_erb___2232672375721569353_70325032812060'
app/views/comments/_comment.html.erb:5:in `_app_views_comments__comment_html_erb___2232672375721569353_70325032812060'
app/views/posts/show.html.erb:76:in `_app_views_posts_show_html_erb___2994099099531367002_70324990819000'

<%= best_in_place comment, comment.body, :as => :textarea %> should be <%= best_in_place comment, :body, :as => :textarea %>

Related

Ruby on Rails 5: Can't Save Record, Unpermitted Parameter for Has Many Through Record

Ruby on Rails 5, Simple Form
Product has many Specifications through ProductSpecs
in Product#Edit, I want to add new Specifications.
if Specifications.save successful, rerender Product. It rerenders products and flashes "success", but the new specification does not persist.
The log indicates unpermitted parameters-- not sure how to correct my product_parameters. I have tried { product_specs => [] } to no avail.
Any help would be greatly appreciated!
Log:
Started PATCH "/products/2" for 127.0.0.1 at 2019-03-07 14:44:24 +0800
Processing by ProductsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"f/wU9o1Fi8jXlTDCiJF93xMXFlaRH6sKx9+lNyg4ZGthVGkhPMrLwES/bEgeeHTHXdXaoolj67FOnGqqULtysg==", "product"=>{"name"=>"Notebooks", "description"=>"Handheld military and medical devices are built to operate in a variety of environments and also built to last.asdfasdfasdf", "category_id"=>"1", "product_spec"=>{"specification"=>{"name"=>"COLD", "low_value"=>"1", "high_value"=>"22", "unit"=>"volts"}}}, "commit"=>"Add New Spec", "id"=>"2"}
Product Load (0.1ms) SELECT "products".* FROM "products" WHERE "products"."id" = ? LIMIT ? [["id", 2], ["LIMIT", 1]]
Setting the product: Notebooks
#<Product id: 2, name: "Notebooks", description: "Handheld military and medical devices are built to...", picture: nil, created_at: "2019-02-20 06:43:20", updated_at: "2019-03-07 05:53:37", iconblack: "icons/products/icon_IPC_black.png", iconwhite: nil, iconyellow: nil, category_id: 1>Unpermitted parameter: product_spec
(0.1ms) begin transaction
Category Load (0.2ms) SELECT "categories".* FROM "categories" WHERE "categories"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
(0.1ms) commit transaction
SUPPOSEDLY UPDATING
Unpermitted parameter: product_spec
product parameters: <ActionController::Parameters {"name"=>"Notebooks", "description"=>"Handheld military and medical devices are built to operate in a variety of environments and also built to last.asdfasdfasdf", "category_id"=>"1"} permitted: true>Redirected to http://localhost:3000/products/2
Completed 302 Found in 7ms (ActiveRecord: 0.5ms)
Started GET "/products/2" for 127.0.0.1 at 2019-03-07 14:44:24 +0800
Processing by ProductsController#show as HTML
Products Controller:
class ProductsController < ApplicationController
# before_action :set_category, only: [:new, :create]
before_action :set_product, only: [:edit, :show, :update, :destroy]
def index
#products = Product.all
#categories = Category.all
#message = Message.new
#message.build_company
end
def new
#product = Product.new
#categories = Category.all
#message = Message.new
#message.build_company
#product.specifications.build
# setting product stuff for testing
#product.picture = "products/IPC_tablet.png"
#product.iconblack = "icons/products/icon_IPC_black.png"
end
def create
#message = Message.new
#message.build_company
#categories = Category.all
#product = Product.new(product_parameters)
#product.category_id = product_parameters[:category_id]
#product_spec = ProductSpec.new
#new_spec= Specification.new
if #product.save!
flash[:success] = "You have saved the #{#product.name} product"
redirect_to product_path(#product)
else
flash.now[:error] = "Product was not saved"
render "new"
end
end
def show
#product = Product.find(params[:id])
#categories = Category.all
#message = Message.new
#message.build_company
#product_specs = #product.product_specs
end
def edit
#message = Message.new
#message.build_company
#categories = Category.all
# To create a new specification through product spec
#product_spec = ProductSpec.new
#new_spec= Specification.new
#product_spec.product = #product
#product_spec.specification = #new_spec
end
def update
# puts "in update product, product parameters: #{product_parameters}"
# puts product_parameters
if #product.update(product_parameters)
flash[:success] = "You have updated the #{#product.name} product"
puts "SUPPOSEDLY UPDATING"
print "product parameters: #{product_parameters.inspect}"
redirect_to product_path(#product)
else
# puts "SUPPOSEDLY NOT UPDATING"
flash.now[:error] = "You have not updated #{#product.name}"
render :edit
end
end
private
def build_company
#message.build_company
end
def set_product
#product = Product.find(params[:id])
puts "Setting the product: #{#product.name}"
print #product.inspect
end
def find_category
#category = Category.find(params[:category_id])
end
def product_parameters
params.require(:product).permit(
:id,
:name,
:description,
:picture,
:category_id,
category: [
:id
],
product_specs: [
{:specification => [] } ]
)
end
end
Product Specs Controller:
class ProductSpecsController < ApplicationController
before_action :find_product, only: [:new, :create, :destroy, :set_product_spec]
before_action :set_product_spec, only: [:destroy, :show]
def new
#product_spec = ProductSpec.new(:product_id => params[:product_id])
end
def create
end
def destroy
#product = Product.find(params[:product_id])
if #product_spec.destroy
flash[:success] = "Product Specification Deleted"
redirect_to product_path(#product.id)
else
flash[:error] = "Oops! Something went wrong"
redirect_to product_path
end
end
private
def find_product
#product = Product.find(params[:product_id])
end
def set_specification
end
def set_product_spec
#product_spec = ProductSpec.find_by(params[:product_id])
end
end
Specifications Controller:
class SpecificationsController < ApplicationController
before_action :set_specification, only: [:edit, :show, :update, :destroy]
def new
end
def create
end
def destroy
end
private
def set_specification
#specification = Specification.find(params[:id])
end
end
Products#Edit Form/View:
<%= simple_form_for #product do |product| %>
<h4 class="product_name">
<%= product.input :name, placeholder: "Product Name" %>
</h4>
<div class="product_picture">
<%= image_tag("products/IPC_tablet.png") %>
</div>
<div class="product_description">
<strong>Description</strong>
<p class="font-size-12">
<%= product.input :description, label: false %>
</p>
<%= product.association :category, prompt: "Select Category" %>
</div>
<div class="product_specifications">
<strong>Specifications</strong>
<!-- RENDER THRU PRODUCT SPECS, EACH EXISTING SPECIFICATION -->
<% if #product_specs %>
<%= product.simple_fields_for :product_specs do |ps| %>
<%= ps.simple_fields_for :specification do |spec| %>
<div class="add_specification">
<div class="specification_fields">
<%= spec.input :name, label: false, input_html: { class: 'spec_input_name' }, placeholder: "Spec" %>
<%= spec.input :low_value, input_html: { class: 'spec_input_values' }, label: false, placeholder:"Lowest Value" %>
<%= spec.input :high_value, input_html: { class: 'spec_input_values' }, label: false, placeholder: "Highest Value" %>
<%= spec.input :unit, label: false, input_html: { class: 'spec_input_values' }, placeholder:"Unit" %>
<%= spec.button :submit, "Save Spec" %>
</div>
</div>
<% end %>
<% end %>
<div>
<strong>Add A New Specification</strong>
</div>
<% end %>
<!-- - - - - - ADD A NEW SPECIFICATION -->
<%= product.simple_fields_for #product_spec do |newps| %>
<%= newps.simple_fields_for #new_spec do |newspec| %>
<div class="add_specification">
<div class="specification_fields">
<%= newspec.input :name, label: false, input_html: { class: 'spec_input_name' }, placeholder: "Spec Name" %>
<%= newspec.input :low_value, label: false, input_html: { class: 'spec_input_values' }, placeholder: "Lowest Value" %>
<%= newspec.input :high_value, label: false, input_html: { class: 'spec_input_values' }, placeholder: "Highest Value" %>
<%= newspec.input :unit, label: false, input_html: { class: 'spec_input_values' }, placeholder: "Unit" %>
<%= newspec.button :submit, "Add New Spec" %>
<% end %>
</div>
<% end %>
</div>
<div class="product_admin_actions">
<%= product.button :submit, "Save This Product" %>
</div>
<% end %>
I think the problem about understanding how accepts_nested_attributes_for works in Rails. I'll try to explain it clearly.
the relation between the models also another important part. If we accept the realtion like: Product -> ProductSpec -> Specification solution must be like this.
# models/product.rb
class Product < ApplicationRecord
has_many :product_specs
accepts_nested_attributes_for :product_specs
end
# models/product_spec.rb
class ProductSpec < ApplicationRecord
has_many :specifications
accepts_nested_attributes_for :specifications
end
# controllers/products_controller.rb
class ProductsController < ApplicationController
...
def create
#proudct = Product.create(product_params)
end
private
def product_params
params.require(:product).permit(
:id,
:name,
:description,
:picture,
:category_id,
product_specs_attributes: [:id,
specifications_attributes: [:id, :name, :low_value, :high_value]
])
end
end
Your view fields looks correct.

using ajax on a form submit rails

Started POST "/users/3/tweets" for 127.0.0.1 at 2018-10-01 16:43:04 +0100
Processing by TweetsController#create as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"a4GACc9npDT1aXdadefb62NbUVbAxA11JBQ/NDkCcPOS0l7wyBbJmwvdPdwZ8rZryT6LmxoFxI9wfv2RloLQIQ==", "tweet"=>{"content"=>"hello"}, "commit"=>"Create Tweet", "user_id"=>"3"}
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 3], ["LIMIT", 1]]
↳ /Users/benherring/.rbenv/versions/2.4.4/lib/ruby/gems/2.4.0/gems/activerecord-5.2.1/lib/active_record/log_subscriber.rb:98
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 3], ["LIMIT", 1]]
↳ app/controllers/tweets_controller.rb:23
(0.1ms) BEGIN
↳ app/controllers/tweets_controller.rb:26
Tweet Create (0.4ms) INSERT INTO "tweets" ("content", "created_at", "updated_at", "user_id") VALUES ($1, $2, $3, $4) RETURNING "id" [["content", "hello"], ["created_at", "2018-10-01 15:43:04.707047"], ["updated_at", "2018-10-01 15:43:04.707047"], ["user_id", 3]]
↳ app/controllers/tweets_controller.rb:26
(1.7ms) COMMIT
↳ app/controllers/tweets_controller.rb:26
Rendering tweets/create.js.erb
Rendered tweets/create.js.erb (7.3ms)
Completed 500 Internal Server Error in 34ms (ActiveRecord: 2.9ms)
ActionView::Template::Error (Missing partial tweets/_index with {:locale=>[:en], :formats=>[:js, :html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :jbuilder]}. Searched in:
* "/Users/benherring/twitter-clone/app/views"
* "/Users/benherring/.rbenv/versions/2.4.4/lib/ruby/gems/2.4.0/gems/devise-4.5.0/app/views"
):
11: <% if #tweet.errors.any? %>
12: refreshForm('<%= j render "tweets/new", user: #user, tweet: #tweet %>');
13: <% else %>
14: addTweet('<%= j render "tweets/index", tweet: #tweet %>');
15: refreshForm('<%= j render "tweet/new", user: #user, tweet: Tweet.new %>');
16: <% end %>
app/views/tweets/create.js.erb:14:in `_app_views_tweets_create_js_erb__1236688757229574759_70092102807800'
im trying to submit a form so that the page doesnt reload, with ajax. the form does work without ajax at the moment, but i want it to be better. ive looked at the rails documentation and on here and i cant get my head around it. ive made changes to the form, controller and made a create.js.erb file but no luck. thanks
class TweetsController < ApplicationController
before_action :authenticate_user!, :except => [:index]
def index
# #tweets = Tweet.all.order("created_at DESC")
#tweets = Tweet.paginate(page: params[:page], per_page: 7).order('created_at DESC')
#tweet = Tweet.new
#user = current_user
end
def show
#tweet = Tweet.find(params[:id])
end
def new
# #tweet = Tweet.new
# #user = current_user
end
def create
# #user = current_user
#user = User.find(params[:user_id])
#tweet = Tweet.new(tweet_params)
#tweet.user = #user
if #tweet.save
respond_to do |format|
format.html { redirect_to user_tweets_path }
format.js
end
else
respond_to do |format|
format.html { render 'tweets/index' }
format.js
end
end
# redirect_to user_tweets_path
end
def edit
#tweet = Tweet.find(params[:id])
end
def update
#tweet = Tweet.find(params[:id])
#tweet.update(tweet_params)
redirect_to tweets_path
end
def upvote
#tweet = Tweet.find(params[:id])
#tweet.upvote_by current_user
# redirect_to :tweets
if request.xhr?
head :ok
else
redirect_to tweets_path
end
end
def downvote
#tweet = Tweet.find(params[:id])
#tweet.downvote_by current_user
redirect_to :tweets
end
private
def tweet_params
params.require(:tweet).permit(:content)
end
end
<%= simple_form_for [ #user ,#tweet], remote: true, id: "form-submit" do |f| %>
<%= f.input :content, label: "Tweet" %>
<%= f.button :submit, class: "btn btn-primary" %>
<% end %>
function refreshForm(innerHTML) {
const newTweetForm = document.getElementById('new_tweet');
newTweetForm.innerHTML = innerHTML;
}
function addTweet(tweetHTML) {
const tweets = document.getElementById('tweets');
reviews.insertAdjacentHTML('beforeend', reviewHTML);
}
<% if #review.errors.any? %>
refreshForm('<%= j render "tweets/new", user: #user, tweet: #tweet %>');
<% else %>
addTweet('<%= j render "tweets/index", tweet: #tweet %>');
refreshForm('<%= j render "tweet/new", user: #user, tweet: Tweet.new %>');
<% end %>
<h1 class="title text-primary">Home</h1>
<div class="tweet-form">
<% if user_signed_in? %>
<%= render 'new',user:#user, tweet:#tweet %>
<% end %>
</div>
<br>
<div id="tweets">
<% #tweets.each do |tweet| %>
<div class="card">
<div class="card-description">
<h4><%= link_to tweet.user.username, user_path(tweet.user) %></h4>
<p class="tweet-content"><%= tweet.content %></p>
<p><%= tweet.created_at.strftime("%B %d %Y, %l:%M%P") %></p>
<%= link_to like_tweet_path(tweet), method: :put do %>
<p>Upvote <%= tweet.get_upvotes.size %>
<% end %>
<%= link_to dislike_tweet_path(tweet), method: :put do %>
Downvote <%= tweet.get_downvotes.size %></p>
<% end %>
</div>
</div>
<% end %>
</div>
<div class="pages">
<%= will_paginate #tweets,renderer: BootstrapPagination::Rails %>
</div>
config.action_view.embed_authenticity_token_in_remote_forms = true
The error you are getting is the javascript response to the form submitting. This line in particular:
addTweet('<%= j render "tweets/index", tweet: #tweet %>')
is the issue.
ActionView::Template::Error (Missing partial tweets/_index with {:locale=>[:en], :formats=>[:js, :html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :jbuilder]}
you must not have a app/views/_tweets file in your application
note that render "tweets/index" automatically adds an underscore to the beginning of the filename passed in so tweets/index becomes tweets/_index.
you need to add a partial (a view file with a leading underscore) that renders the index template
I think you got a typo in your js.erb
const tweets = document.getElementById('tweets');
reviews.insertAdjacentHTML('beforeend', reviewHTML);
did you mean tweets instead of reviews in the second line?
also in the js.erb
function refreshForm(innerHTML) {
const newTweetForm = document.getElementById('new_tweet');
newTweetForm.innerHTML = innerHTML;
}
But this will render a form inside the form, shouldn't you get the parent element for that. In your case is the class tweet-form.
Your logs show this error:
ActionView::Template::Error (Missing partial tweets/_index
That's caused by this code:
addTweet('<%= j render "tweets/index", tweet: #tweet %>');
Apparently, you don't have a partial called tweets/_index to render.
Could you create this file and make sure it's named _index not index?

Rails 5: Unpermitted parameter: :image

I have a two forms inside my edit action, one is to update an item inside the item.rb model(which works fine)... and the other one is to create an image in a attachment.rb model. The problem is that it creates a row inside the db images with null values and does not save the actually image along with the correct values.
items_contoller.rb
def edit
#attachment = Attachment.new
end
this is the form for the image create:
<%= form_for #attachment, url: create_attachment_path(#attachment), :html => {:id => "form", :multipart => true }, method: :post do |form| %>
<% if #attachment.errors.any? %>
<div class="centerList">
<div id="error_explanation">
<h2><%= pluralize(item.errors.count, "error") %> <%= t 'store_item_edit_4' %></h2>
<% #attachment.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</div>
</div>
<% end %>
<%= hidden_field_tag :item_id, value: #item.id %>
<div class="form-group">
<div class="text-center">
<label class="btn btn-primary"><%= t 'store_item_edit_5' %><span style="display:none;">
<%= form.file_field :image, multiple: true, id: "uploads" %></span></label>
<%= form.submit '', :style => "display: none;" %>
<% end %>
this is the route:
post "attachments/create"=> "attachments#create", :as => :create_attachment
attachments_controller.rb
def create
#attachment = Attachment.new(attachment_params)
respond_to do |format|
if #attachment.save
format.html { redirect_back fallback_location: root_path, notice: 'Image was successfully uploaded.' }
format.json { render :show, status: :created, location: #attachment }
else
format.html { render :new }
format.json { render json: #attachment.errors, status: :unprocessable_entity }
end
end
end
def attachment_params
params.require(:attachment).permit(:item_id, :account_id, :image)
end
and this is what I get inside the console... at some point as you can see I get a Unpermitted parameter: :image:
started POST "/attachments/create" for 127.0.0.1 at 2018-03-14 17:20:23 +0200
Processing by AttachmentsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"6kgGVoUf2tlM2YdxZis6xavw//zC4azttYi4FFshgw4swiFUIOfb58hCtZxf0If2ihOXz3SCETQSnci6l1IFIA==", "item_id"=>"{:value=>44}", "attachment"=>{"image"=>[#<ActionDispatch::Http::UploadedFile:0x007fc6e4acfb18 #tempfile=#<Tempfile:/var/folders/hq/pr4rt14n7s31v3f6292wtjm00000gn/T/RackMultipart20180314-4193-1jrij48.jpg>, #original_filename="image1.jpg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"attachment[image][]\"; filename=\"image1.jpg\"\r\nContent-Type: image/jpeg\r\n">]}}
Store Load (0.5ms) SELECT "stores".* FROM "stores" WHERE "stores"."id" = $1 ORDER BY "stores"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]]
Unpermitted parameter: :image
(0.2ms) BEGIN
SQL (0.4ms) INSERT INTO "attachments" ("created_at", "updated_at") VALUES ($1, $2) RETURNING "id" [["created_at", "2018-03-14 15:20:23.368574"], ["updated_at", "2018-03-14 15:20:23.368574"]]
(1.2ms) COMMIT
Redirected to https://localhost:3000/store/items/edit/44
Completed 302 Found in 8ms (ActiveRecord: 2.3ms)
Any ideas how to fix this:
You should add:
def attachment_params
params.require(:attachment).permit(:item_id, :account_id, image: {})
end

Issues with update action using acts_as_votable

I'm currently getting the votes to hit the database but I'm now having issues getting the update action to work in my controller. The votes don't record with the update action but do without out it. However, I then get a missing template error for Pits#update. Any help is appreciated. Thanks.
Terminal Error
Started PUT "/pits/3" for 127.0.0.1 at 2014-08-21 11:38:25 -0500
Processing by PitsController#update as JS
Parameters: {"id"=>"3"}
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = 4 ORDER BY "users"."id" ASC LIMIT 1
Pit Load (0.2ms) SELECT "pits".* FROM "pits" WHERE "pits"."user_id" = ? AND "pits"."id" = ? LIMIT 1 [["user_id", 4], ["id", 3]]
Completed 404 Not Found in 64ms
ActiveRecord::RecordNotFound (Couldn't find Pit with 'id'=3 [WHERE "pits"."user_id" = ?]):
app/controllers/pits_controller.rb:37:in `update'
I currently have
Pits Controller
class PitsController < ApplicationController
def new
#pit = Pit.new
end
def index
#pit = Pit.all
#user = User.find_by(params[:id])
#pits = Pit.paginate(:page => params[:page]).order('created_at ASC').group_by { |pit| pit.created_at.strftime("%B %Y") }
end
def create
#user = current_user
#pit = current_user.pits.create(pit_params)
if #pit.save
redirect_to #pit
else
render 'new'
end
end
def show
#pit = Pit.find(params[:id])
end
def edit
end
def update
#user = current_user
#pit = current_user.pits.find(params[:id])
if #pit.update_attributes(pit_params)
redirect_to #pit
end
end
private
def pit_params
params.require(:pit).permit(:topic, :summary, :image, :video_url, :author, :user_id)
end
end
Comments Controller
class CommentsController < ApplicationController
def create
#pit= Pit.find(params[:pit_id])
#comment = #pit.comments.build(comments_params)
#comment.user = current_user
#comment.save
redirect_to pit_path(#pit)
end
def destroy
#pit = Pit.find(params[:pit_id])
#comment = #pit.comments.find(params[:id])
#comment.destroy
redirect_to pit_path(#pit)
end
def upvote
#pit = Pit.find(params[:pit_id])
#comment = #pit.comments.find(params[:comment_id])
#comment.upvote_by current_user
redirect_to pit_path(#pit)
end
def downvote
#pit = Pit.find(params[:pit_id])
#comment = #pit.comments.find(params[:comment_id])
#comment.downvote_from current_user
redirect_to pit_path(#pit)
end
def update
end
def show
end
private
def comments_params
params.require(:comment).permit(:body, :user_id, :votable, :voter, :vote_scope)
end
end
_comment.html.erb
<div class = "well">
<p>
<strong>Comment:</strong>
<%= comment.body %>
<p>posted by: <%= comment.user.name %></p>
<%= link_to "Like", pit_comment_like_path(#pit, comment), method: :put , :remote => true %>
<%= link_to "Dislike", pit_comment_dislike_path(#pit, comment), method: :put, :remote => true %>
</p>
<p>
<%if comment.user == current_user %>
<%= link_to 'Destroy Comment', [#pit, comment],
method: :delete,
data: { confirm: 'Are you sure?' } %>
<% end %>
</p>
</div>
Not sure about everything you have going on here, but I suspect the error has to do with use current_user to find the pit. If the current_user is not the user_id for the pit, it won't find any pit (exactly your error).
Try adjusting to this and it should be able to find the pit propperly.
def update
#pit = Pit.find(pit_params[:id])
if #pit.update_attributes(pit_params)
redirect_to #pit
end

Ajax with Polymorphic Association (Destroy & Create)

I have a polymorphic association with dailyposts & comments in my rails app
Everything works fine in the database, but when I try to add Ajax to the Destroy Action (I used this tutorial http://railscasts.com/episodes/136-jquery-ajax-revised)
....it doesn't work unless I refresh the page. (but my alert works in destroy.js.erb)
I know my error is in destroy.js.erb
New to Rails...Please help :)
This is my code...
ROUTES
resources :dailyposts do
resources :comments
end
CONTROLLERS
##Dailyposts
class DailypostsController < ApplicationController
respond_to :html, :js
def show
#user = User.find_by_username(params[:username])
#dailypost = Dailypost.find_by_id(params[:id])
#commentable = #dailypost
#comments = #commentable.comments.arrange(:order => :created_at)
#comment = Comment.new
end
end
##Comments
class CommentsController < ApplicationController
before_filter :load_commentable
respond_to :html, :js
def create
#comment = #commentable.comments.create(params[:comment])
#comment.user = current_user
if #comment.save
respond_to do |format|
format.html { redirect_to #commentable }
format.js
end
else
redirect_to #commentable, notice: "Comment can't be blank."
end
end
def destroy
#comment = Comment.find(params[:id])
#commentable = #comment.commentable
if #comment.destroy
respond_to do |format|
format.html { redirect_to #commentable }
format.js
end
end
end
private
def load_commentable
resource, id = request.path.split('/')[1, 2]
#commentable = resource.singularize.classify.constantize.find(id)
end
end
VIEWS
Dailypost show.html.erb
<div class="row-fluid">
<div class="span12">
<div>
<%= raw(dailypost_with_links(#dailypost)) %>
</div>
<%= render "comments/form" %>
<div id="comments">
<%= nested_comments #comments %>
</div>
</div>
</div>
_comment.html.erb
<section class="comments">
<div class ="user">
<%= link_to comment.user.username, comment.user %>
<%= comment.content %>
</div>
##Here I am passing remote: true for ajax
<% if current_user?(comment.user) %>
<%= link_to content_tag(:i, "", class: "icon-trash icons"), [#commentable, comment], method: :delete,
data: { confirm: "Are you sure?" },
title: "Delete", remote: true %> |
<% end %>
</section>
destroy.js.erb
##alert is working
alert('ajax works!');
$('#<%= dom_id(#comment) %>').remove();
LOGS
Started DELETE "/dailyposts/11/comments/133" for 127.0.0.1 at 2013-08-04 23:06:31 -0700
Processing by CommentsController#destroy as JS
Parameters: {"dailypost_id"=>"11", "id"=>"133"}
Dailypost Load (0.3ms) SELECT "dailyposts".* FROM "dailyposts" WHERE "dailyposts"."id" = ? ORDER BY dailyposts.created_at DESC LIMIT 1 [["id", "11"]]
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."remember_token" = 'sgFH2XeZWEXCcjxiAwgfXg' LIMIT 1
Comment Load (0.2ms) SELECT "comments".* FROM "comments" WHERE "comments"."id" = ? LIMIT 1 [["id", "133"]]
Dailypost Load (0.1ms) SELECT "dailyposts".* FROM "dailyposts" WHERE "dailyposts"."id" = 11 ORDER BY dailyposts.created_at DESC LIMIT 1
(0.1ms) begin transaction
Comment Load (0.1ms) SELECT "comments".* FROM "comments" WHERE (comments.ancestry like '133/%' or comments.ancestry = '133')
SQL (0.4ms) DELETE FROM "comments" WHERE "comments"."id" = ? [["id", 133]]
(2.3ms) commit transaction
Rendered comments/destroy.js.erb (0.7ms)
Completed 200 OK in 25ms (Views: 10.3ms | ActiveRecord: 3.9ms)
Try this:
Dailypost show.html.erb
<div id="comments">
<%= render #comments %>
</div>
_comment.html.erb
<div id="<%= dom_id(comment) %>">
<%= comment.content %>
</div>
create.js.erb
$('<%= escape_javascript(render(:partial => #comment))%>').appendTo('#comments').hide().fadeIn();
destroy.js.erb
$('#<%= dom_id(#comment) %>').remove();
The redirect is breaking the response. Try changing it to redirect_to( :back ) unless request.xhr?
The problem is in destroy.js.erb , the second line does not work because there is no id like edit_comment_1 of the format edit_comment_(:id).
In your _comment.html.erb, add an appropriate div with id that is used in your .js.erb
<section class="comment">
<div id="edit_comment_<%= comment.id %>">
<div class ="user">
<%= link_to comment.user.username, comment.user %>
<%= comment.content %>
</div>
<% if current_user?(comment.user) %>
<%= link_to content_tag(:i, "", class: "icon-trash icons"), [#commentable, comment], method: :delete,
data: { confirm: "Are you sure?" },
title: "Delete", remote: true %> |
<% end %>
</div>
</section>

Resources