Does anybody have any tips for managing polymorphic nested resources in Rails 3?

Posted by Ryan on Stack Overflow See other posts from Stack Overflow or by Ryan
Published on 2010-09-10T00:31:07Z Indexed on 2010/12/23 4:54 UTC
Read the original article Hit count: 193

in config/routes.rb:

resources posts do
  resources comments
end

resources pictures do
  resources comments
end

I would like to allow for more things to be commented on as well.

I'm currently using mongoid (mongomapper isn't as compatible with rails3 yet as I would like), and comments are an embedded resource (mongoid can't yet handle polymorphic relational resources), which means that I do need the parent resource in order to find the comment.

Are there any elegant ways to handle some of the following problems:

in my controller, I need to find the parent before finding the comment.

if params[:post_id]
  parent = Post.find(params[:post_id]
else if params[:picture_id]
  parent = Picture.find(params[:picture_id]
end

which is going to get messy if I start adding more things to be commentable

also url_for([comment.parent,comment]) doesn't work, so I'm going to have to define something in my Comment model, but I think I'm also going to need to define an index route in the Comment model as well as potentially an edit and new route definition.

There might be more issues that I have to deal with as I get further.

I can't imagine I'm the first person to try and solve this problem, are there any solutions out there to make this more manageable?

© Stack Overflow or respective owner

Related posts about ruby-on-rails-3

Related posts about polymorphism