每个belongs_to has_many关联是否需要嵌套路由?

时间:2013-04-15 22:02:47

标签: ruby-on-rails ruby-on-rails-3 routes associations

这是一个相当基本的问题,但我还没能在网上找到具体的答案。每个has_many belongs_to都不需要嵌套路由正确吗?您是否只在查找class/:id/class/:id表格的网址时才使用嵌套路线?

例如,我们说我有两个课程ProfilePost

模型/简档

has_many :posts

模型/后

belongs_to :profile

没有单独的post网址,posts会显示在profiles/show中。 post路由(在这种情况下它只是像:new,:create和:destroy这样的操作)是否应该嵌套在:profiles资源中? rails指南指出资源不应该嵌套多于一层深度,而且通常有多次。为每个关联创建嵌套资源似乎很快就会违反此规则。提前谢谢!

2 个答案:

答案 0 :(得分:3)

如果您没有使用/profile/1/posts/profile/1/posts/1,则不需要嵌套路由。但是,我建议您重新考虑,嵌套路由可以实现干净的RESTful API

例如,整齐的小嵌套路线:

resources :profile, :shallow => true do
  resources :posts
end

将为您提供所有这些真正有用的路线:

   profile_posts GET    /profile/:profile_id/posts(.:format)     posts#index
                 POST   /profile/:profile_id/posts(.:format)     posts#create
new_profile_post GET    /profile/:profile_id/posts/new(.:format) posts#new
       edit_post GET    /posts/:id/edit(.:format)                posts#edit
            post GET    /posts/:id(.:format)                     posts#show
                 PUT    /posts/:id(.:format)                     posts#update
                 DELETE /posts/:id(.:format)                     posts#destroy
   profile_index GET    /profile(.:format)                       profile#index
                 POST   /profile(.:format)                       profile#create
     new_profile GET    /profile/new(.:format)                   profile#new
    edit_profile GET    /profile/:id/edit(.:format)              profile#edit
         profile GET    /profile/:id(.:format)                   profile#show
                 PUT    /profile/:id(.:format)                   profile#update
                 DELETE /profile/:id(.:format)                   profile#destroy

这样,您必须在必要/有用时自由选择嵌套路线,例如

GET /profile/:profile_id/posts/new(.:format) # create a new post for the given profile_id
GET /profile/:profile_id/posts(.:format) # return all posts for the given profile_id

并使用不需要嵌套路由的浅路线

答案 1 :(得分:1)

如果您阅读Ruby on Rails指南的第2.7节,则说明:

  

嵌套路线允许您在路线中捕获此关系。

请参阅 - http://guides.rubyonrails.org/routing.html#resource-routing-the-rails-default以供参考。

除此之外,您可能希望对具有usercreate等的edit类执行特定操作...每个用户都与特定预订相关联。这意味着无论何时对用户做任何事情,您都会对用户/预订做些什么。因为这与此相关。

RESTful路由是一种设置应用程序并充分利用统一资源标识符的简洁方法。这样的一个例子是识别特定用户,例如/ users / 1 / bookings / 3,这将显示第一个用户。