之间有什么区别
namespace :alpha do
resources :posts
end
和
resources :alpha do
resources :posts
end
答案 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博文中了解scope
和namespace
之间的区别。