rails嵌套路由中的资源和命名空间之间有什么区别

时间:2016-07-30 15:51:31

标签: ruby-on-rails ruby

之间有什么区别
namespace :alpha do
  resources :posts
end

resources :alpha do
  resources :posts
end

1 个答案:

答案 0 :(得分:4)

使用rake routes检查差异。

这个带名称空间的定义:

namespace :alpha do
  resources :posts
end

产生以下路线:

         Prefix Verb   URI Pattern                     Controller#Action
    alpha_posts GET    /alpha/posts(.:format)          alpha/posts#index
                POST   /alpha/posts(.:format)          alpha/posts#create
 new_alpha_post GET    /alpha/posts/new(.:format)      alpha/posts#new
edit_alpha_post GET    /alpha/posts/:id/edit(.:format) alpha/posts#edit
     alpha_post GET    /alpha/posts/:id(.:format)      alpha/posts#show
                PATCH  /alpha/posts/:id(.:format)      alpha/posts#update
                PUT    /alpha/posts/:id(.:format)      alpha/posts#update
                DELETE /alpha/posts/:id(.:format)      alpha/posts#destroy

正如您所看到的,唯一与普通resources路由集不同的是添加/alpha前缀。

现在为两级resources路由定义:

resources :alpha do
  resources :posts
end

导致:

         Prefix Verb   URI Pattern                               Controller#Action
    alpha_posts GET    /alpha/:alpha_id/posts(.:format)          posts#index
                POST   /alpha/:alpha_id/posts(.:format)          posts#create
 new_alpha_post GET    /alpha/:alpha_id/posts/new(.:format)      posts#new
edit_alpha_post GET    /alpha/:alpha_id/posts/:id/edit(.:format) posts#edit
     alpha_post GET    /alpha/:alpha_id/posts/:id(.:format)      posts#show
                PATCH  /alpha/:alpha_id/posts/:id(.:format)      posts#update
                PUT    /alpha/:alpha_id/posts/:id(.:format)      posts#update
                DELETE /alpha/:alpha_id/posts/:id(.:format)      posts#destroy
    alpha_index GET    /alpha(.:format)                          alpha#index
                POST   /alpha(.:format)                          alpha#create
      new_alpha GET    /alpha/new(.:format)                      alpha#new
     edit_alpha GET    /alpha/:id/edit(.:format)                 alpha#edit
          alpha GET    /alpha/:id(.:format)                      alpha#show
                PATCH  /alpha/:id(.:format)                      alpha#update
                PUT    /alpha/:id(.:format)                      alpha#update
                DELETE /alpha/:id(.:format)                      alpha#destroy

如您所见,alpha成为包含所有8条RESTful路由的顶级资源。反过来,posts成为第二级资源,只能通过指向特定alpha对象的路径访问。

Rails Routing from the Outside In中阅读更多内容。

您可能还会发现有趣的scope选项。在Scoping Rails Routes博文中了解scopenamespace之间的区别。