开发者

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

开发者 https://www.devze.com 2023-02-09 06:44 出处:网络
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'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]

  d开发者_运维百科ef 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:

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

You'll find examples there.

0

精彩评论

暂无评论...
验证码 换一张
取 消