When to use Nested Controllers in your Rails apps

29 Sep 2009
by Michael Cindric

Nested controllers are great. I don't care that they have a stigma attached to them they work well and make sense especially if your rails application has a Admin section for example. This allows you to easy separate the admin logic into its own controllers etc keeping your code clean and easy to manage.

So thats what we are going to do for this example.

Step 1. Create your admin controller

You can use whichever process works best for you, but for this we are going to use script/generate:

 ./script/generate controller admin

Step 2. Create your user controller

You can use whichever process works best for you, but for this we are going to use script/generate:

 ./script/generate controller admin/users

Step 3. Check to ensure proper inheritance

The nested users controller should look something like so:

class Admin::UsersController < ApplicationController
end

Step 4. Create the Routes

The nested users controller should look something like so:

map.namespace :admin do |admin|
  admin.resources :users
end

Before rails 2+ you had to do like like we have below. Personally l don't mind it makes it a little easier to read but either option works fine

map.resource(:admin) do |admin|
  admin.resources(:users, :controller => 'admin/users')
end

Step 5. Wait there is no step 5 your done

Now when you need to link to any of these actions its very simple keeping in mind that users is nested under the admin controller so all you have to do to create a link that goes to the index action on the nested users controller is add the admin prefix before

 link_to "Users", admin_users_url

The same applies when you are wanting to link to the show action of users all you do is loose the "s" on users as you would normally

 link_to "View User", admin_user_url(@user)

You can see a list of all the routes you have available to you by going to the root directory of your project in terminal and typing

rake routes

Have an idea? Get in touch