Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 854
nishanthan Avatar asked Oct 05 '12 14:10

nishanthan


People also ask

Can CanCan can?

The can-can (also spelled cancan as in the original French /kɑ̃kɑ̃/) is a high-energy, physically demanding dance that became a popular music-hall dance in the 1840s, continuing in popularity in French cabaret to this day.

Can Rails ability?

CanCan is an authorization library for Ruby on Rails that defines the authorization of specific resources for multiple users. All these permissions are set in a single locality (the Ability class) and are not duplicated across controllers, views, or database queries.


1 Answers

...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
like image 192
willglynn Avatar answered Oct 01 '22 19:10

willglynn