Nested controller routes (Rails 2 and 3)

Updated . Posted . Visible to the public.

In order to keep the controllers directory tidy, we recently started to namespace controllers. With the :controller option you can tell Rails which controller to use for a path or resource. For nested resources, Rails will determine the view path from this option, too.

That means the following code in routes.rb

resources :users do
  resource :profile, controller: 'users/profiles' #[1]
end

… makes Rails expect the following directory structure:

app/
  controllers/
    users/
      profiles_controller.rb
    users_controller.rb
  ...
  views/
    users/
      profiles/
        show.html.haml
      index.html.haml
      ...

Note:

  • the user profiles controller must be named Users::ProfilesController
  • [1] specifying the controller as 'user/...' would make Rails expect views in view/user/... (singular)

The better approache might be to use a module. See this card on how to namespace with modules

Dominik Schöler
Last edit
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2013-08-21 18:34)