In my tickets.js.coffee:
$.ajax '/comments/add',
type: 'POST',
dataType: 'html'
success: ( data ) ->
alert 'success'
<%= form_for @comment, :url => user_ticket_message_comments_path( @user, @ticket, m ), :html => { :class => "add-comment", :id => "add-comment-" + @ticket.id.to_s } do |f| %>
<%= f.label :body, "Add comment" %>
<%= f.text_area :body %>
<%= f.hidden_field :message_id, :value => m.id %>
<%= f.submit "Add comment" %>
<% end %>
Comments table:
id | message_id | body
----------------------
CommentsController:
def create
@comment = params[:comment]
@comment.save
end
My routes.rb:
resources :messages do
resources :comments
end
I get this error:
undefined method `save' for {"body"=>"awef", "message_id"=>"15"}:ActiveSupport::HashWithIndifferentAccess
Comment belongs to a Message and Message has many comments.
Where should I look to fix this error?
params[:comment]is aHash, not aCommentobject, and thus can’t be “saved”. You need to create a newCommentobject and assign each attribute to it, then save theCommentobject:Depending on how “new” your app is,
config.active_record.whitelist_attributesmay be set totrue, in which case the above will give you a security error and you should read the Rails Guides on Mass-Assignment for more information about how to properly assign attributes (you should actually read it either way).