Reputation: 11232
This example shows how to create a form for an associated model 'Comment', where 'Comment' belongs_to 'Post' and 'Post has_many 'Comments'.
http://edgeguides.rubyonrails.org/getting_started.html#generating-a-controller
How might I modify that to display all the comments in the form, and still have it call the CommentsController (versus having the form call the PostsController, as in the example here http://railscasts.com/episodes/17-habtm-checkboxes)?
Thanks
UPDATE:
To ask a different way: Using a Polymorphic Assocation, if Photo and Article each 'has_many' Comments, the comment form should call the CommentsController, as shown here http://railscasts.com/episodes/154-polymorphic-association -- But what if I'm editing multiple comments in one form for a given Photo. In this case should the form still call the CommentsController or is it better off calling the PhotoController?
Upvotes: 0
Views: 282
Reputation: 16084
Here's the updated answer:
I'd still use the CommentsController
to do all the updating of comments. Unless you're editing the post and its comments at the same time. Since you're editing a post's comments, what you can do is just POST
them to an action in the comments controller. In your view, make a form with a fields_for
for each comment.
Then, they can all post to an update_multiple
(or something similarly named) action in the CommentsController
. It's just a matter of accepting the params hash and parsing it properly.
def update_multiple
# I'd expect the params hash to look like:
# {"comments" => {"1" => {"body" => "my body"}, "comment_2" => {"body" => ""}}
# To keep your controllers thing, stick it into the model!
if Model.update_multiple params[:comments]
respond_to do |f|
#...
end
end
end
In your model (just make it more robust by doing it all in a transaction, so if one fails, then none of them are updated. Well, that's really up to you):
def self.update_multiple(hash)
updated_all = true
hash.each do |key, value|
comment = self.find key.to_i
updated_all = false unless comment.update_attributes(value)
end
updated_all
end
Upvotes: 1