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 :bar do
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])
But if it’s Bar I need to do:
@commentable = Bar.find(params[:bar_id])
What I do now is to use this method:
params.each do |name, value|
if name =~ /(.+)_id$/
@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?