Is it possible to use cancan with two ability classes

I am using rails 3.0.9, cancan 1.6.7 and developing 1.4.8

I use two development models (User and Admin) for different registration and registration processes

So, I want to share the abilities that depend on the registered user (resource), because there are more than 70 models and only 10 models are common for both types of users (here, more than 50 models and views are used only by Admin users)

I want to implement two skill classes (UserAbility and AdminAbility), and the helper method current_user / current_admin should be passed to UserAbility / AdminAbility

Example:

In ApplicationController.rb

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

From my questions above,

  • Perhaps there are several classes of features in cancan, if possible, how to create them, because I tried

    rails g cancan:user_ability

    but I got an error like Could not find the cancan: user_ability generator .

  • How to choose the appropriate skill class for the registered user / administrator.

  • If both the user and the administrator are accessing the controller, how can I get the currently registered User / Admin object

Is there any other solution for this?

Anyone please help solve this problem.

+6
source share
3 answers

... that you can use several feature models directly if you want:

 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 
+12
source

For this you do not need several classes of features:

 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 call Ability.new() any model, but that's fine, as you can check which object you got. Of course, you can delegate other objects if you want; it's all just Ruby.

+7
source

I will add to what answergiynn answered . It seems I had to add some more codes to make it work. I found the answer from this post

Add the following to application_controller.rb

  def current_ability if admin_signed_in? @current_ability ||= Ability.new(current_admin) else @current_ability ||= Ability.new(current_user) end end 
0
source

Source: https://habr.com/ru/post/927032/


All Articles