给定一条记录检索授权用户:通过 cancan 读取它
Given a record retrieve users authorized to :read it via cancan
我有一个使用 cancan 进行授权的 rails 项目。更新记录时,我想通知有权阅读记录的用户该记录已更新。 Cancan 很容易让我检查特定用户是否有权对记录执行操作或获取允许特定用户操作的检索记录。但是我可以通过康康舞做相反的事情吗? IE。给定特定记录检索所有有权对其执行操作的用户?
given a specific record retrieve all users authorized to perform an action on it?
没有
这就像问 "can Devise show me all the users who are currently logged in?" - 它没有能力去做,因为范围不存在。
有几种方法可以实现您想要的。
最简单的方法是将通知(我不确定你是怎么做到的)推送到应用程序的前端(这样,任何人可以阅读)。
然后,正如CallmeSurge
所说,您将能够在其上使用can? read
,以便只有符合条件的用户才能实际调用数据:
#app/views/layouts/application.html.erb
<%= [[notification]] if can? :read, [[notification]] %>
--
另一种方法是使用 ActiveRecord return 用户有资格阅读您已经使用的标准的通知。这可以使用以下方法完成:
#app/models/user.rb
class User < ActiveRecord::Base
def self.notify
where(x: y)
end
end
那么您就可以按如下方式设置通知:
User.notify.each do |user|
user.notification.create .....
end
我对康康的熟悉程度一般。话虽如此,这就是我能想到的:
@myrecord = MyRecord.find(1)
authorized_user_ids = User.find_each do |user|
user.id if Ability.new(user).can? :read, @myrecord
end.compact
puts authorized_user_ids
# => [1, 2, 5, 10, 78]
但是请注意,这是非常低效的,因为它会遍历所有用户。您可能希望使用您要实现的单独 table/model 来执行缓存。
我有一个使用 cancan 进行授权的 rails 项目。更新记录时,我想通知有权阅读记录的用户该记录已更新。 Cancan 很容易让我检查特定用户是否有权对记录执行操作或获取允许特定用户操作的检索记录。但是我可以通过康康舞做相反的事情吗? IE。给定特定记录检索所有有权对其执行操作的用户?
given a specific record retrieve all users authorized to perform an action on it?
没有
这就像问 "can Devise show me all the users who are currently logged in?" - 它没有能力去做,因为范围不存在。
有几种方法可以实现您想要的。
最简单的方法是将通知(我不确定你是怎么做到的)推送到应用程序的前端(这样,任何人可以阅读)。
然后,正如CallmeSurge
所说,您将能够在其上使用can? read
,以便只有符合条件的用户才能实际调用数据:
#app/views/layouts/application.html.erb
<%= [[notification]] if can? :read, [[notification]] %>
--
另一种方法是使用 ActiveRecord return 用户有资格阅读您已经使用的标准的通知。这可以使用以下方法完成:
#app/models/user.rb
class User < ActiveRecord::Base
def self.notify
where(x: y)
end
end
那么您就可以按如下方式设置通知:
User.notify.each do |user|
user.notification.create .....
end
我对康康的熟悉程度一般。话虽如此,这就是我能想到的:
@myrecord = MyRecord.find(1)
authorized_user_ids = User.find_each do |user|
user.id if Ability.new(user).can? :read, @myrecord
end.compact
puts authorized_user_ids
# => [1, 2, 5, 10, 78]
但是请注意,这是非常低效的,因为它会遍历所有用户。您可能希望使用您要实现的单独 table/model 来执行缓存。