Create polymorphic resources

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

Hey,

I usually do it like you have already written it, but if you feel
uncomfortable with it let me make 2 suggestions (those are quick & dirty
and not tested)

  1. In your commentcontroller:

@commentable = params[:foo_id] ? Foo.find(params[:foo_id] :
Bar.find(params[:bar_id]

this should work with some tweaking (dont know if it works out of the
box,
as said, didnt test it) and would be best used if only two models have
comments.

  1. In your commentcontroller:

Is to work with some kind of before_filter to determine the commentable
object and classify it.

However, I would stay with the above pattern posted by you because it
makes
it a breeze to add a third, …, n model to it.

Sincerly,
Crispin

Am Donnerstag, 28. Februar 2013 21:11:32 UTC+1 schrieb Linus P.:

I think the best way to go is with the hidden fields. whats your problem
with those?