Rails中的多态路由 – 在视图中

我将Comment作为多态模型。

它附在Post,Review等上。

我在CommentsController中也有一个动作,名为test

我有我的路由设置,所以test_post_comment_path工作(调用CommentsController中的test操作)。

问题是,在我的部分视图中,我希望该路由能够根据当前操作进行更改,即。 在test_post_comment_path时,在Post和test_review_comment_path上是test_review_comment_path

正确的方法是使用polymorphic_url …

只需使用两条不同的路径?

我的意思是:你不想在路线中加入太多逻辑。

如果路线尝试做的不仅仅是路线,那么第一次出现问题时你会遇到严重问题。

在您的局部视图中,创建特定链接或其他html注释内容的逻辑应该在帮助器中。

这样的事情:(在你的局部视图中)

 @commentable.each |commentable| test_#{commentable.class.to_s.downcase}_comment_path end 

如果它是’post’那么它将生成’test_post_comment_path’,如果是审查,它将生成test_review_comment_path

我决定在视图中使用if语句,基于当前操作是否存在,例如@post或@review