1

我一直在当前项目中使用位掩码来跟踪用户角色,但现在有一种情况,我需要能够为所有具有特定角色的用户进行查找。

我的角色设置如下:

  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

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

4

1 回答 1

7

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"} }

你会在那里找到例子。

于 2011-02-05T21:13:15.017 回答