Skip to content

Instantly share code, notes, and snippets.

@matthaliski
Last active August 29, 2015 14:02
Show Gist options
  • Save matthaliski/ab24a670f0b35316d1d7 to your computer and use it in GitHub Desktop.
Save matthaliski/ab24a670f0b35316d1d7 to your computer and use it in GitHub Desktop.
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment