Ruby on Rails Thursday, February 28, 2013

Hi


I have created a polymorphic association for comments since I need commenting functionality on several models. The issue is that when I create the comment in my Commets#create action, I really don't know what type the parent is of.

So, let's say I have Foo, Bar and Comment. Comment have this:
  belongs_to :commentable, polymorphic: true

And Foo and Bar both have:
  has_many :comments, as: :commentable

In my routes.rb I nest the comments:
  resources :foo do
    resources :comments
  end

  resources :bar do
    resources :comments
  end

A new comment is posted to /foo/1/comments or /bar/1/comments. When I'm in the Comments#create action, how am I supposed to create the comment through either Foo/Bar?

If it is a comment for a Foo resource, I need to do:
@commentable = Foo.find(params[:foo_id])
@commentable.comments.create(....)

But if it's Bar I need to do:
@commentable = Bar.find(params[:bar_id])
@commentable.comments.create(....)

What I do now is to use this method:
 def find_commentable
  params.each do |name, value|
    if name =~ /(.+)_id$/
      return $1.classify.constantize.find(value)
    end
  end
  nil
 end

and

@commentable = find_commentable

Which loops over all params for something that ends with _id and then get the class name from that etc... But that feels a bit "hackish" to me :S Another solution would be to add the "commentable_id" and "commentable_type" as hidden fields in my Comment form.


How do you handle this issue? Are there better ways than the way above?

Cheers

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msg/rubyonrails-talk/-/V8lO_B42uQsJ.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

No comments:

Post a Comment