Archive for August, 2010

Creating an admin area in Rails

This is an answer I posted to a question on Stack Overflow. The title of that question is a little off from what the writer actually wanted to know, so I decided to to re-post the answer here. It’s a bit of an easy/basic topic, but it comes up a lot, so I thought other people out there might find it useful.

The two things to keep in mind when making an admin area are

  1. you can create namespaces for routes to get the /admin URLs you’re looking for and
  2. you can have controllers inherit from other descendants of ActionController

So to make an admin area, you’d want to have RESTful resources declared in a namespace (assumes Rails 3 routes):

1
2
3
4
5
6
7
8
9
10
11
# routes.rb
resources :users
resources :posts
resources :pages

namespace :admin do |admin|
  match '/' => 'dashboard#index'
  resources :users
  resources :posts
  resources :pages
end

The top set is the public ones and the bottom set gives you the admin routes like /admin/users/new and /admin/posts/1, etc. I’m also assuming you might want a “dashboard” so I’m setting up a route to the index method of an Admin::DashboardController

Then you create an admin base controller that descends from ApplicationController. Use it to hold your admin area layout and your authentication filters:

1
2
3
4
class Admin::BaseController < ApplicationController
  before_filter :require_user
  layout 'admin'
end

Now make a directory in app/controllers called “admin”. Make controllers in there as normal, but have them inherit from your base controller:

1
2
3
4
# pages_controller.rb
class Admin::PagesController < Admin::BaseController
  # Controller code in here
end

Make a corresponding directory in app/views for “admin” and you’re good to go — everything is namespaced out and views/controllers would behave like you think.

You can always run “rake routes” to see all the admin routes.

Tags: