所以我在应用程序中使用Cancancan gem。我已通过Devise / Omniauth gem和 Admins 对 Users 进行了身份验证,并通过简单的自定义身份验证对它们进行了身份验证。 我想实现
ability.rb
def initialize(userOrAdmin)
if userOrAdmin.user?
can :read, User
return unless user.present?
can :manage, User, id: user.id
elsif userOrAdmin.admin?
can [:update, :read] , Admin, id: admin.id
end
end
end
但这不起作用。 我试图覆盖这样的能力方法
application_controller
def current_ability
if current_admin?
@current_ability ||= Ability.new(current_admin)
elsif current_user?
@current_ability ||= Ability.new(current_user)
end
end
但是我收到 方法current_admin错误 ,可能是因为Cancancan从设备中假定了current_admin,但尽管我使用了自己的current_admin方法,却找不到它。>
我还尝试为User.rb和Admin.rb中的枚举分配角色,并正确更改capability.rb,但是我得到了 未定义方法admin?用户错误
Cancancan verion 2.0
答案 0 :(得分:1)
我找到了可行的解决方案 application_controller.rb
def current_ability
if current_user
return if current_admin.present?
@current_ability ||= Ability.new(current_user)
elsif current_admin
return unless current_admin.present?
@current_ability ||= Ability.new(current_admin)
end
end
结束
ability.rb
class Ability
include CanCan::Ability
def initialize(userOrAdmin)
if userOrAdmin.is_a? User
can :read, User
can [:update, :read], User, id: userOrAdmin.id
elsif userOrAdmin.is_a? Admin
can :read, Admin
can [:update, :read], Admin, id: userOrAdmin.id
end
end
end
这可以正常工作,没有错误。每当我同时以用户身份和管理员身份登录时,管理员角色就会出现“无法授权错误”。
答案 1 :(得分:0)
搜索后,我发现了一些有用的文章:
我建议您尝试以下操作:
# Ability.rb
class Ability
include CanCan::Ability
def initialize(user)
# Everyone:
can :read, User
# Users:
return unless user.present?
can :manage, User, user_id: user.id
# Admins:
return unless user.admin?
can :manage, :all
end
end
# Routes.rb
devise_for :users # current_user:
devise_for :admins # current_admin:
# Application_Controller.rb
def current_ability
@current_ability ||= current_admin ? AdminAbility.new(current_admin) : UserAbility.new(current_user)
end