views:

14

answers:

1

I'm watching a Ryan Bates screencast on polymorphic relationships, and he uses this private method for finding all comments related to a nested model.

So I could find all the comments of a given Post with this :

def find_commentable
  params.each do |name, value|
    if name =~ /(.+)_id$/
      return $1.classify.constantize.find(value)
    end
  end
  nil
end

And then used by:

@commentable = find_commentable
@comments = @commentable.comments

The comments are published with this form :

- form_for [@commentable, Comment.new] do |f|
  = f.label :text, 'Comment'
  %br/
  = f.text_area :text, :style => "height: 100px;"
  %br/
  = f.submit "Submit"

But what if on the same page, I would like to have a form for every comment? How would I set up a form_for for that, and what would its controller have to specify?

A: 

What I did was began with the find_commentable method and split it this way:

def find_commentable
  params.each do |name, value|
    if params[:comment]
      return Comment.find(params[:comment][:id])
    elsif name =~ /(.+)_id$/
      return $1.classify.constantize.find(value)
    end
  end
  nil
end

And the ID is passed as a hidden_field from the form.

From there, the regular controller will take care of the save.

Trip