2013-04-15 71 views
1

这是一个相当基本的问题,但我一直没能在网上找到具体的答案。每个has_many belongs_to不需要嵌套路由是否正确?当你在寻找形式为class/:id/class/:id的网址时,你是否应该只使用嵌套路线?每个belongs_to has_many关联是否需要嵌套路由?

例如,假设我有两个类ProfilePost

型号/配置文件

has_many :posts 

型号/后

belongs_to :profile 

有没有单独的post URL时,posts显示在profiles/show。如果post路由(在这种情况下,它只是像new,:create和destroy的行为)嵌套在:profiles资源中?导轨指南指出,资源不应嵌套超过一个级别,并且经常有多次。为每个关联制作嵌套资源似乎会很快违反此规则。提前致谢!

回答

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 

,并使用浅的路线,其中嵌套的路线是没有必要的

+0

因此,最好的做法是使帖子成为配置文件的嵌套资源? – Steve

+0

我确实这么认为。请重新阅读答案,我已经添加了一些更多信息。特别是关于':shallow => true'。但最终它取决于你想要什么。如果你100%肯定你永远不想使用浅层路线,那么当然,就把它们排除在外。 –

1

如果你读了Ruby on Rails的指南第2.7节它指出:

嵌套路由让你捕捉到你的路由这种关系。

参见 - http://guides.rubyonrails.org/routing.html#resource-routing-the-rails-default仅供参考。

除此之外,您可能想要对类别执行特定操作,即user其中createedit等......每个用户都与特定预订相关联。这意味着只要你对用户做任何事情,你确实在为用户/预订做些事情。因为这与此相关。

RESTful路由是一种干净的方式来设置您的应用程序并充分利用统一资源标识符。一个例子就是识别一个特定的用户,比如/ users/1/bookings/3这会显示第一个用户。

相关问题