Skip to content

How To: Add an Admin Role

Joshua Dance edited this page Feb 23, 2015 · 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  
end

Adjust the generated migration:

Devise 2.2:

class DeviseCreateAdmins < ActiveRecord::Migration
  def self.up
    create_table(:admins) do |t|
      t.string :email,              :null => false, :default => ""
      t.string :encrypted_password, :null => false, :default => ""
      t.integer  :sign_in_count, :default => 0
      t.datetime :current_sign_in_at
      t.datetime :last_sign_in_at
      t.string   :current_sign_in_ip
      t.string   :last_sign_in_ip
      t.integer  :failed_attempts, :default => 0 # Only if lock strategy is :failed_attempts
      t.string   :unlock_token # Only if unlock strategy is :email or :both
      t.datetime :locked_at
      t.timestamps
    end
  end

  def self.down
    drop_table :admins
  end
end

Earlier Devise Versions:

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

Your migration will not look like this:

class AddAdminToUsers < ActiveRecord::Migration
  def change
    add_column :users, :admin, :boolean
  end

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

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

Next, execute the migration script:

$ rake db:migrate

Now you're able to 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