Rails route namespacing (in different flavors)

Updated . Posted . Visible to the public. Repeats.

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 vs scope

The main difference between namespace and scope 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
Dominik Schöler
Last edit
Felix Eschey
Keywords
routes, routing
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2016-03-01 11:02)