我正在开发有用户的Rails应用程序。角色是我有管理员/玩家的另一张桌子。我们已经在角色模型和用户模型之间实现了has_many through
关联。
每个用户可以是Player或Admin或两者都可以。只有具有管理员角色的用户才能将角色分配给其他用户。
所以我的问题是我无法根据用户的角色来限制用户。我已使用cancancan宝石进行授权。我试图创建正确的能力,现在所有用户都可以为自己分配角色,这是我不想要的。我希望只有具有管理员角色的用户才能分配角色并执行所有操作。所有其他用户应该只能删除/更新其详细信息。我发现“ if user.admin?”此代码无法正常工作。如果我给elsif user.player?它给错误未定义的方法。
class Ability
include CanCan::Ability
def initialize(user)
if user.admin?
can :manage, :all
else
can :update, User, id: user.id
can :destroy, User , id: user.id
end
end
end
我也尝试了以下代码
class Ability
include CanCan::Ability
def initialize(user)
if user.Role.name.admin?
can :manage, :all
elsif user.Role.name.player?
can :update,User, id: user.id
can :destroy,User , id: user.id
end
end
end
Please help me with proper guidance.