简体   繁体   English

使用角色掩码查找具有特定角色的所有用户

[英]using a roles mask to find all users who have a certain role

I've been using a bitmask in a current project for keeping track of user roles, but now have a situation where I need to be able to do a find for all users who are a certain role. 我在当前项目中一直使用位掩码来跟踪用户角色,但是现在遇到的情况是我需要能够为具有特定角色的所有用户进行查找。

I have my roles set-up like so: 我的角色设置如下:

  ROLES = %w[admin editor moderator contributor]

  def roles
    ROLES.reject do |r|
      ((roles_mask || 0) & 2**ROLES.index(r)).zero?
    end
  end

  def roles=(roles)
    self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.sum
  end

  def role_symbols
    roles.map(&:to_sym)
  end

I can find all users with exactly the same bit map, but not sure how to extract one particular role, in this case all users which have the roles "editor". 我可以找到具有完全相同位图的所有用户,但不确定如何提取一个特定角色,在这种情况下,所有具有角色“编辑者”的用户都将找到。

On http://railscasts.com/episodes/189-embedded-association , Ryan Bates provides a scope to search: http://railscasts.com/episodes/189-embedded-association上 ,Ryan Bates提供了搜索范围:

named_scope :with_role, lambda { |role| {:conditions => "roles_mask & #{2**ROLES.index(role.to_s)} > 0"} }

You'll find examples there. 您将在此处找到示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM