Read more

Nested controller routes (Rails 2 and 3)

Dominik Schöler
August 21, 2013Software engineer at makandra GmbH

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.

Illustration online protection

Rails professionals since 2007

Our laser focus on a single technology has made us a leader in this space. Need help?

  • We build a solid first version of your product
  • We train your development team
  • We rescue your project in trouble
Read more Show archive.org snapshot

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

Posted by Dominik Schöler to makandra dev (2013-08-21 20:34)