深层嵌套的多态资源值得付出努力吗?

时间:2012-05-30 06:40:14

标签: ruby-on-rails-3 polymorphic-associations custom-routes nested-routes

我正处于我的开发阶段,我认为深度(> 1)嵌套资源不值得付出努力。

我有这样的事情:

  resources :first-level do
    resources :comments
    resources :second-level do
      resources :comments      
      resources :first-child do
        resources :comments
      end
      resources :second-child do
        resources :comments
      end
      resources :third-child do
        resources :comments
      end
    end
  end

踢球者的评论是其他资源的多态性。我的目的是拥有干净的网址,如〜/ first-level / 34 / comments,〜/ first-level / 34 / second-level / 56 / third-level / comments等。

到目前为止,问题是嵌套时的多态路由只会导致悲伤。我正在关注几个Ryan Bates Railscasts作为例子。例如,如果我尝试在第一级使用polymorphic_path它工作正常,我得到:

polymorphic_path([@commentable, comments]) => ~/first-level/34/comments

~/first-level/34/second-level/23上的相同代码失败了:

undefined method 'second-level_comment_path' for #<#<Class:0x007fcc4acfbe58>:0x007fcc4ae73d08>但是当我查看我的路线时,实际命名的路线是first-level_second-level_comment。我尝试手动创建second-level_comment_path基本上为first-level_second-level_comment的别名,但我似乎无法做到这一点。

除非有人可以在这里指出一个明显的错误,否则我倾向于这种方法(http://weblog.jamisbuck.org/2007/2/5/nesting-resources)并且只是取消嵌套这些。我有一个面包屑风格的导航来显示层次结构,所以应该足够了,我越是看它,网址确实有点笨拙。

1 个答案:

答案 0 :(得分:1)

使用嵌套资源时,您需要在要访问子级别时指定所有父级别。否则Rails将不知道如何达到您的孩子级别。因此,您需要使用first-level_second-level_comment并提供如下所示的第一级和第二级值:

first-level_second-level_comments_path(@my_first_level, @my_second_level)

将呈现:

~/first-level/34/second-level/23/comments

编辑:

我不明白为什么你需要逐步构建路径。

您始终可以构建first_level注释路径:

first-level_comments_path(@my_first_level)

将呈现

~/first-level/34/comments

或者列出第一级中的所有第二级:(给定第一级的第二级索引操作)

first-level_second-levels_path(@my_first_level)

将呈现

~/first-level/34/second-levels
相关问题