2016-07-30 95 views

回答

3

退房的差異之間的差異資源和命名空間之間的區別。

這個定義與命名空間:

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條REST風格的路線頂級資源。反過來,posts成爲第二級資源,只能通過路徑訪問特定的對象。

瞭解更多Rails Routing from the Outside In

您可能還會感興趣的scope選項。閱讀和namespace之間的區別Scoping Rails Routes博客文章。