matthaliski
6/11/2014 - 7:01 PM

Testing for admin role using Devise

Testing for admin role using Devise

Create your devise User model

We start by getting devise up and running and generating the User model.

rails generate devise User

Then you'll probably run rake db:migrate and follow their instructions for making sure you have a few default things in order. Okay, so far so good.

Add a role column to Users

We're going to identify the user as an admin with the help of enum. So let's generate a migration

rails generate migration add_role_to_users

Pop that sucker open and add

class AddRoleToUsers < ActiveRecord:Migration
  def change
    add_column :users, :role, :integer
    # Make sure all potentially existing users are set to just plain old users
    User.update_all role: 0
  end
end

Define the roles

In user.rb add the following

enum role: [:user, :admin]
after_initialize :set_default_role, if => :new_record?

private

  def set_default_role
    self.role ||= :user
  end

Then what?

Well, now you're in the position to create a helper. For example:

module SessionHelper

  def admin_user?
    if current_user.try(:role)
      if current_user.role == 'admin'
        true
      end
    end
  end
end

And that's cool, because you can test in your controllers. Maybe something like:

def update
  if admin_user?
    @posts = Post.all
  end
end