我一直在当前项目中使用一个位掩码,以便跟踪用户角色,但现在我需要能够为某个角色的所有用户做一个查找的情况。

我有我的角色设置如下:

  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
.

我可以找到具有完全相同的位映射的所有用户,但不确定如何提取一个特定的角色,在这种情况下所有具有角色“编辑器”的用户。

有帮助吗?

解决方案

http://reailscasts.com/episodes/189-embedded-association ,Ryan Bates提供了一个搜索范围:

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

你会在那里找到一个例子。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top