views:

18

answers:

1

I would like some suggestions on how to do this the best way:

I have a Rails application that handles comments. Each comment belongs to a context, such as a forum topic, or an image. The context reference is polymorphic.

I have partial that displays the comment, and that partial also holds links to edit or delete it for example. The links are generated using "edit_comment_path(the_comment)" and "comment_path(the_comment)", etc.

Now, what I would like is to include the context in those links: instead of a link to "/comments/38" i would like them to link to "/images/5/comments/38" and "/topics/3/comments/63" ...

The comments are only nested in one level, so there will never be a "/forums/18/topics/17/comments/74" link for example.

The application should have enough information to generate those links. But what is the best way to do that?

+1  A: 

I think what you're looking for is the polymorphic_path helper. Assuming that you have an instance of the correct association in the view, you can create the paths like the following examples:

edit_polymorphic_path([@image, the_comment]) # => /images/5/comments/38/edit

polymorphic_path([@topic, the_comment]) # => /topics/3/comments/63

These specs can be nested arbitrarily deep. See here for more.

bjg
Great! That's *exactly* what I was looking for!
Jonatan
@Jonatan: And @bjg: You can even do this `[:edit, @image, the_comment]` and `[@topic, the_comment]. `polymorphic_path` will be called internally so Rails can understand what you want.
Ryan Bigg