opensoul.org

Using a singleton resource for an admin section

February 5, 2007 code 2 min read

Applications with an admin section often have a URL like http://myapp.com/admin, with that URL being a summary page, and all the other admin pages be under that URL (like, http://myapp.com/admin/users to edit users.). Without defining a lot of routes, this hasn’t been very easy with Rails…until now. Singleton resources have been merged into the 1.2 branch from edge-rails, so I thought I would share a little pattern that I’ve been using in several of my apps to accomplish this.

Singleton resources are like regular resources in Rails 1.2, except that they don’t have an :id parameter. This happens to work perfectly for using one controller to show a summary page, and then nesting the routes for other controllers inside of it.

The routes definition looks like this:

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

Update: The key here is map.resource (singular).

To make this work, generate an admin controller:

script/generate controller admin

You can now set up the “show” action in the admin controller to display a summary page.

The named route users\_path now generates the URL /admin/users.

This content is open source. Suggest Improvements.

@bkeepers

avatar of Brandon Keepers I am Brandon Keepers, and I work at GitHub on making Open Source more approachable, effective, and ubiquitous. I tend to think like an engineer, work like an artist, dream like an astronaut, love like a human, and sleep like a baby.