Alexander Rühle, March 07, 2015 14:54
I've often asked myself what exactly the difference between namespace and scope is.
This is the simple option. It will prefix the generated path and the path name. And it also assumes that the controller is to be found under a module named in the same manner as the namespace itself.
namespace :management do
resources :users
end
Generated routes:
Prefix Verb URI Pattern Controller#Action
management_users GET /management/users(.:format) management/users#index
POST /management/users(.:format) management/users#create
management_user GET /management/users/:id(.:format) management/users#show
PATCH /management/users/:id(.:format) management/users#update
PUT /management/users/:id(.:format) management/users#update
DELETE /management/users/:id(.:format) management/users#destroy
Scope can give you a more accurate result but is a bit more complex at the same time.
When using scope without any options and only a scope name, it will just add a prefix for the generated path.
scope :management do
resources :users
end
Prefix Verb URI Pattern Controller#Action
users GET /management/users(.:format) users#index
POST /management/users(.:format) users#create
user GET /management/users/:id(.:format) users#show
PATCH /management/users/:id(.:format) users#update
PUT /management/users/:id(.:format) users#update
DELETE /management/users/:id(.:format) users#destroy
"module" lets you define another module and only the module.
scope module: 'management' do
resources :users
end
Prefix Verb URI Pattern Controller#Action
users GET /users(.:format) management/users#index
POST /users(.:format) management/users#create
user GET /users/:id(.:format) management/users#show
PATCH /users/:id(.:format) management/users#update
PUT /users/:id(.:format) management/users#update
DELETE /users/:id(.:format) management/users#destroy
"path" will prefix the generated path
scope module: 'management', path: 'fu' do
resources :users
end
Prefix Verb URI Pattern Controller#Action
users GET /fu/users(.:format) management/users#index
POST /fu/users(.:format) management/users#create
user GET /fu/users/:id(.:format) management/users#show
PATCH /fu/users/:id(.:format) management/users#update
PUT /fu/users/:id(.:format) management/users#update
DELETE /fu/users/:id(.:format) management/users#destroy
"as" can be used to change the name of the path method used to identify the resources.
scope module: 'management', path: 'fu', as: 'awesome' do
resources :users
end
Prefix Verb URI Pattern Controller#Action
awesome_users GET /fu/users(.:format) management/users#index
POST /fu/users(.:format) management/users#create
awesome_user GET /fu/users/:id(.:format) management/users#show
PATCH /fu/users/:id(.:format) management/users#update
PUT /fu/users/:id(.:format) management/users#update
DELETE /fu/users/:id(.:format) management/users#destroy