Naomi K
Naomi K

Reputation: 1447

how to make admin users using devise and cancan?

I set up devise and cancan, but how do I make 1 user admin and other user not admin now? Do I use omniauth (I want to only log in with google), devise, or cancan?

Upvotes: 3

Views: 9356

Answers (4)

zeantsoi
zeantsoi

Reputation: 26193

To get this particular functionality within CanCan to work, you'll want to store an attribute on your Devise User model that indicates whether a particular user is an admin, or not.

Start by creating an attribute on your User table called admin:

# from command line
rails generate migration AddAdminToUser user

In the migration, set the default value for the admin attribute to false (or true, depending on what behavior you want enacted by default):

class AddAdminToUser < ActiveRecord::Migration
  def change
    add_column :users, :admin, :boolean, :default => true

  end
end

Run the migration

# from command line
rake db:migrate

In your User model, create a convenience method to access the value of admin:

# app/models/user.rb    
def admin?
    admin
end

Then, in ability.rb, define the abilities you want to set for each user:

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user (not logged in)
    if user.admin? # Admin user
      can :manage, :all
    else # Non-admin user
      can :read, :all
    end
  end
end

Remember – by default, a new User is not an admin. You can always enable admin privileges on an existing user in the following manner:

# from the Rails console
user = User.find(some_number)
user.update_attribute(:admin, true)

Upvotes: 16

Faiq Adam
Faiq Adam

Reputation: 107

add_column :users, :admin, :boolean, :default => true

change default true to false

add_column :users, :admin, :boolean, :default => false

Upvotes: 2

Jakub Kuchar
Jakub Kuchar

Reputation: 1665

Its kind of "Up to you", but the easy was just boolean attribute to the user something like admin = true/false and then you can define ability.rb something like:

class Ability
  include CanCan::Ability

  def initialize(user)
    # Define abilities for the passed in user here. For example:
    #
    #   user ||= User.new # guest user (not logged in)
    #   if user.admin?
    #     can :manage, :all
    #   else
    #     can :read, :all
    #   end
  end
end

Upvotes: 0

Related Questions