==>我有一个网站,其名称空间如下所示
User::xyz_controller
User::abc_controller
Admin:xyz_controller
Admin:abc_controller
==> 具有三个角色的用户模型
admin
leader
consultant
如果用户具有角色领导者或顾问。他只应访问用户名称空间控制器。以及用户是否具有管理员角色。管理员只能访问 Admin命名空间控制器。
==>以下是我的 ability.rb 文件内容。
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
答案 0 :(得分:0)
应用程序控制器
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
在控制器中定义
-> 不带类使用
load_and_authorize_resource class: false
-> 与类一起使用
load_and_authorize_resource class: Company