Skip to content

How To: Add an Admin Role

egtann edited this page Nov 1, 2012 · 37 revisions

Option 1 - Creating an admin model

First generate the model and migration for the Admin role:

$ rails generate devise Admin

Configure your Admin model

class Admin < ActiveRecord::Base
  devise :database_authenticatable, :trackable, :timeoutable, :lockable  
  attr_accessible :email, :password, :password_confirmation
end

Adjust the generated migration:

class DeviseCreateAdmins < ActiveRecord::Migration
  def self.up
    create_table(:admins) do |t|
      t.database_authenticatable :null => false
      t.trackable
      t.lockable
      t.timestamps
    end
  end

  def self.down
    drop_table :admins
  end
end

Routes should be automatically updated to contain the following

 devise_for :admins

Enjoy!

Option 2 - Adding an admin attribute

The easiest way of supporting an admin role is to simply add an attribute that can be used to identify administrators.

$ rails generate migration add_admin_to_users admin:boolean

Add this to the migration:

class AddAdminToUsers < ActiveRecord::Migration
  def self.up
    add_column :users, :admin, :boolean, :default => false
  end

  def self.down
    remove_column :users, :admin
  end
end

Next, execute the migration script:

$ rake db:migrate

Now you're able to do identify administrators:

if current_user.admin?
  # do something
end

If the page could potentially not have a current_user set then:

if current_user.try(:admin?)
  # do something
end

With the above way if current_user were nil, then it would still work without raising an undefined method `admin?' for nil:NilClass exception.

The code below can be used to grant admin status to the current user.

current_user.update_attribute :admin, true
Clone this wiki locally