Is it possible to use cancan with two ability class
...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
You don't need multiple ability classes for that:
class Ability
include CanCan::Ability
def initialize(user_or_admin)
user_or_admin ||= User.new
common_rules(user_or_admin)
if user_or_admin.kind_of? Admin
admin_rules(user_or_admin)
else
user_rules(user_or_admin)
end
end
def common_rules(user_or_admin)
# can :verb, :noun
end
def admin_rules(admin)
can :manage, :all
end
def user_rules(user)
can :read, :all
end
end
CanCan will ultimately be calling Ability.new()
with either model, but that's perfectly fine, since you can check what kind of object you received. You can, of course, delegate to other objects if you prefer; it's all just Ruby.