Search code examples
ruby-on-railsdevisecancancancancan

Devise with CanCan(can)


I can't seem to find a good tutorial for this and I've hit a bit of a wall.

I'm using rails 4.2.0 with a basic CRUD app. For auth I'm using devise and for roles I'm using Cancancan as these have fairly understandable documentation.

I have two types of Users:

Users and Admins.

Admins can interact with all models. Add-Edit-Delete etc.

Users can only interact with certain models. Which will be a booking system of sorts.

I'm not quite sure of the process I need to go through to set this up. Do I need to do a full rails generation for each user type or can I just use the Devise generation? Adding onto that how can I choose the user type? So far I have two login links which works.

The main issue I'm having is defining roles in cancancan.

Any help/questions on the subject would be appreciated.


Solution

  • For simplicity, you could add an admin boolean column on the users table. You would check for an admin user with user.admin?.

    Here is what the migration will look like.

    > rails g migration add_admin_to_users

    In your migration file, I would set a default value to false prior to running it.

    class AddAdminToUsers < ActiveRecord::Migration
      def up
        add_column :users, :admin, :boolean, null: false, default: false
      end
    
      def down
        remove_column :users, :admin
      end
    end
    

    By default, your users won't be admins. However, you can easily make a user an admin with user.update_column(:admin, true).

    With this, you should be able to follow the CanCanCan docs, as they are pretty extensive I believe.

    class Ability
      include CanCan::Ability
    
      def initialize(user)
        user ||= User.new
    
        if user.admin?
          # admin abilities
        else
          # non-admin abilities
        end
      end
    end
    

    http://github.com/CanCanCommunity/cancancan/wiki/Defining-Abilities