【发布时间】:2021-08-06 16:45:37
【问题描述】:
我扩展了用户模型,允许我对用户进行.can? 检查。
class User < ApplicationRecord
def ability
@ability = Ability.new self
end
delegate :can?, :cannot?, :to => :ability
end
这使我可以执行@some_user.can? :edit, Book 之类的操作并获得结果。 (cancan 视图助手,但在模型中。)。这很好用。
我希望能够反过来做,并让所有可以执行操作的用户。
示例:给我所有可以:编辑、图书的用户。 User.can? :edit, Book 返回一个活动记录集合。
为了让它发挥作用,我这样做了;
class User < ApplicationRecord
def self.can? sym, obj, *args
uids = []
User.all.each do |user|
uids << user.id if user.can? sym, obj, args
end
User.where id: uids
end
end
虽然这行得通,但感觉真的很恶心,因为它要遍历每个用户,而且我担心规模……有没有更快的方法来做到这一点??
【问题讨论】:
标签: ruby-on-rails ruby cancan cancancan