开发者

Augmenting Bates' `find_commentable` method

开发者 https://www.devze.com 2023-01-22 03:39 出处:网络
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.

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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消