Search code examples
ruby-on-railsruby-on-rails-3devisecancan

Is it possible to use cancan with two ability class


I'm using rails 3.0.9, cancan 1.6.7 and devise 1.4.8

I'm using two devise models(User and Admin) for different log-in and registration process

So I want to divide the abilities depend upon the logged-in user(resource), because there are more than 70 models and only 10 models are common for both type of users(here more than 50 models and views are only used by Admin users)

I want to implement two Ability class(UserAbility and AdminAbility) and the devise helper method current_user/current_admin should be passed to UserAbility/AdminAbility

Example:

In ApplicationController.rb file

    def current_ability
        if current_user
            @current_ability = UserAbility.new(current_user)
        elsif current_admin
            @current_ability = AdminAbility.new(current_admin)
        end
    end

From the above my questions,

  1. Is multiple ability class is possible in cancan, if possible then how to create it because I tried

    rails g cancan:user_ability

    but I got error as Could not find generator cancan:user_ability.

  2. How to choose the appropriate Ability class for the logged-in User/Admin.

  3. If a controller is accessed by both the User and Admin, then how can I get the currently logged-in User/Admin's object

Is there any other solution for this?

Any one please help to solve this


Solution

  • ...that said, you can use multiple ability models directly if you prefer:

    class UserAbility
      include CanCan::Ability
    
      def initialize(user)
        can :read, :all
      end
    end
    
    class AdminAbility
      include CanCan::Ability
    
      def initialize(admin)
        can :manage, :all
      end
    end
    
    class ApplicationController < ActionController::Base
      # overriding CanCan::ControllerAdditions
      def current_ability
        if current_account.kind_of?(AdminUser)
          @current_ability ||= AdminAbility.new(current_account)
        else
          @current_ability ||= UserAbility.new(current_account)
        end
      end
    end