-1

==> I have a website with two names spaces as below

User::xyz_controller

User::abc_controller

Admin:xyz_controller

Admin:abc_controller

==> User model with three roles

admin leader consultant

If the user has role leader or consultant. He should only access the User namespace controllers. and if User has role Admin. Admin should only access the Admin namespace controllers.

==> below is my ability.rb file content.

class Ability include CanCan::Ability def initialize(user) if user.has_role? :Admin can :manage, :all elsif user.has_role? :Leader cannot :manage, User elsif user.has_role? :Consultant cannot :manage, User end end end

wish
  • 43
  • 6

1 Answers1

0

Application Controller

before_action :current_ability, unless: :devise_controller?

private

def current_ability

controller_name_segments = params[:controller].split('/')

controller_name_segments.pop

controller_namespace = controller_name_segments.join('/').camelize

Ability.new(current_user, controller_namespace)

end

ability.rb

class Ability

include CanCan::Ability

def initialize(user, namespace)

case namespace

when 'Admin'

can :manage, :dashboard if user.has_role? :Admin

can :manage, Company if user.has_role? :Admin

can :manage, CompanyHistory if user.has_role? :Admin

can :manage, Record if user.has_role? :Admin

can :manage, Service if user.has_role? :Admin

can :manage, ProcessTable if user.has_role? :Admin

can :manage, User if user.has_role? :Admin

when 'Users'

can :manage, Company if user.has_role? :Consultant

can :manage, CompanyHistory if user.has_role? :Consultant

can :manage, Record if user.has_role? :Consultant

can :manage, Company if user.has_role? :Leader

can :manage, CompanyHistory if user.has_role? :Leader

can :manage, Record if user.has_role? :Leader

end

end

end

Define in controller

--> Use without class

load_and_authorize_resource class: false

--> Use with class

load_and_authorize_resource class: Company

Community
  • 1
  • 1
wish
  • 43
  • 6