Rails Can 可以为多种设计型号提供能力等级
我想知道如何定义一个能力类别并根据已登录的用户提供该能力类别。
我正在使用 Active Admin、Can Can 和 Devise,并且我已成功创建了一个 User 和一个 AdminUser 模型。
我的能力.rb中有这个
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
if (user)
can :manage, Item
end
end
end
现在我已经使用这个wiki条目来确定我们确实可以定义一个自定义能力文件并使用它来代替能力.rb:
https://github.com/ryanb/cancan/wiki/changing-defaults
但我想做的是,如果“非-admin 用户”已登录并自定义abilty(如果用户管理员已登录)。
附带问题:是否可以实现这样我不需要自定义权限并且可以在一个ability.rb 文件中设置权限?
I was wondering how I can define an ability class and serve that ability class depending on the user that has logged in.
I am using Active Admin, Can Can and Devise and I have successfully created a User and an AdminUser models.
I have this in my ability.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
if (user)
can :manage, Item
end
end
end
Now I have used this wiki entry to determine that we can indeed define a custom ability file and use that instead of the ability.rb:
https://github.com/ryanb/cancan/wiki/changing-defaults
But what I wanted to do is, be able to use ability.rb if a "non-admin user" is signed in and a custom abilty if a user admin is signed in.
Side Question: Could it be done such that I don't need a custom one and I could set permissions in one ability.rb file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我从未真正使用过 ActiveAdmin,所以我不完全确定我是否遗漏了某些内容,但该框架似乎并不依赖于 CanCan。这就是为什么我假设您正在定义一个
current_ability
方法,如 wiki 中所述,并且它是使用Ability.new(current_user)
实例化的。如果是这种情况,并且您的
current_user
可以是User
或AdminUser
,那么在中检查这一点就没有问题>Ability
类:您可以简单地查看用户的类型并相应地更改规则。您还可以使用
is_a?
而不是kind_of?
进行更严格的检查,但这可能不是必需的,并且如果您稍后决定进行继承,则可能会导致问题。您可以检查的另一种方法是在两个模型中定义一个
admin?
方法。这可能是一个更好的方法,因为显式类型检查在 ruby 中并不是很流行——它通常会限制您的选择。它可能看起来像这样:I've never really used ActiveAdmin, so I'm not entirely sure if I'm missing something, but it doesn't seem like that framework relies on CanCan. That's why I'm assuming you're defining a
current_ability
method like explained in the wiki and it's instantiated withAbility.new(current_user)
.If that's the case, and your
current_user
can be either aUser
or anAdminUser
, then there's no problem in checking for that in theAbility
class:You can simply take a look at the user's type and change the rules accordingly. You can also use
is_a?
instead ofkind_of?
for stricter checking, but it's probably not required and might cause issues if you decide to do inheritance later on.Another way you could check is by defining an
admin?
method in both models. This might be a better way to do it, since explicit type checking is not very popular in ruby -- it often limits your choices. It might look like this: