在routes.rb中适当地嵌套资源

时间:2013-12-17 23:36:39

标签: ruby-on-rails ruby routes ruby-on-rails-4 nested-attributes

我的应用程序已经深度嵌套了资源,但在阅读http://guides.rubyonrails.org/routing.html#shallow-nesting之后,我意识到拥有这些深层嵌套的资源并不明智。这是我的路线目前所处的情况。

resources :assortments do
  resources :comments do
    member do
      post :like
      post :unlike
    end
  end
  member do
    post :like
    post :unlike
  end
  resources :designs do
    resources :comments do
      member do
        post :like
        post :unlike
      end
    end
    member do
      post :like
      post :unlike
      get :likes
    end
  end
end

我想知道组织这种结构的正确方法,以减少混乱和“正确”。或者我还好吗?
感谢。

1 个答案:

答案 0 :(得分:1)

您可以在顶部shallow: true指定resources :assortments,并自动为所有嵌套路线构建浅路线。

我也会将:comments资源转移到关注点,就像那样

concern :commentable do
  resources :comments do
    member do
      :like
      :unlike
    end
  end
end

resources :assortments, shallow: true do
  concerns :commentable
  ...
  resources :designs do
    concerns :commentable
  end
end

在一个不相关的主题上,我会考虑让LikesController拥有一个集中的喜欢处理资源,当你喜欢多元化喜欢的事情时,可能会让人头疼。