문제

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:

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

You'll find examples there.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top