TL;DR There are three dimensions you can control when scoping routes:
scope module: 'module', path: 'path', as: 'as' do
resources :examples, only: :index
end
→ Path Helpers: as_examples_path
and as_examples_url
→ URLs: /path/examples
→ Controller module: Module::ExamplesController
and views location: app/views/module/examples/
These options work with resources
as well, e.g. resources :examples, path: 'demonstration'
namespace
vsscope
The main difference between
namespace
andscope
is:
namespace
sets all three dimensions as default and you have to opt out any of the three dimensions for customization.scope
sets none of the three dimensions as default and you have to opt in any of the three dimensions for customization.
Examples
Changing URLs only
When you want to namespace some paths but leave the corresponding controllers and url helpers unaffected, you can use the scope method like follows:
scope path: 'proxy' do
resources :properties
end
- URL:
/proxy/properties
- Route helper:
properties_path
- Controller class:
PropertiesController
A typical use case is the customer asking you to change some URLs.
Namespace controllers and path helpers without changing URLs
When you want to namespace your controller classes (group some controllers into a folder) but leave the corresponding routes unaffected, you can use the namespace
method like follows:
namespace 'proxy', path: '/' do
resources :properties
end
- URL:
/properties
- Route helper:
proxy_properties_path
- Controller class:
Proxy::PropertiesController
Without affecting path helpers
When you want to namespace some resources of your application, but keep plain route helpers, you can use the scope method like follows:
scope module: 'proxy', path: 'proxy' do
resources :properties
end
- URL:
/proxy/properties
- Route helper:
properties_path
- Controller class:
Proxy::PropertiesController