开发者

Make rails resource system decide the context for an entity

开发者 https://www.devze.com 2023-01-12 09:27 出处:网络
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 refe

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 inc开发者_StackOverflow社区lude 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消