Search code examples
ruby-on-railsdeviseomniauthcancan

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?


Solution

  • 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)