【问题标题】:Ruby CanCanCan reverse user lookup, faster way to do this?Ruby CanCanCanCanCan 反向用户查找,更快的方法来做到这一点?
【发布时间】: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


    【解决方案1】:

    我建议将cancan与rolify gem结合使用,rolify可以为用户预先设置角色,然后您的问题将变成查询拥有edit Book role的用户

    member_user.add_role :read, Book
    admin_user.add_role :edit, Book
    
    # query
    User.with_role(:edit, Book) # [admin_user]
    User.without_role(:edit, Book) # [member_user]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-20
      • 2018-05-03
      • 1970-01-01
      相关资源
      最近更新 更多