蒙古语语法问题

| 在Railscasts的第189集中,用户模型中有一个命名范围,如下所示:
field :roles_mask,      :type => Integer
ROLES = %w[admin moderator author]

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

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

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

 def role_symbols
  roles.map(&:to_sym)
 end
当我尝试了多种选择而无法正常工作时,如何将其用于Mongoid?     
已邀请:
        那段Railscasts实际上是为不支持将数组作为本机类型(Mongoid支持)的数据库设计的。然后,您可以创建一个使用数组查询条件之一的范围。 例如:
class User
  include Mongoid::Document

  field :email
  field :roles, :type => Array

  ROLES = %w[admin moderator author]

  class << self
    def with_role(*args)
      any_in(:roles => args)
    end
  end
end
本示例将允许您传递单个角色
User.with_role(\"admin\")
或角色数组
User.with_role(\"moderator\", \"author\")
,而后者则返回主持人或作者的用户。     
        您可以使用for_js方法使用通过mongoid公开的本机地图归约mongoDB机制 http://www.rubydoc.info/github/mongoid/mongoid/Mongoid/标准:for_js
ROLES.each_with_index do |role, role_index|
  scope \"#{role.to_s.pluralize}\", -> { self.for_js(\"(this.roles_mask & (1 << role_val)) > 0\", role_val: role_index) }
end
这将给出以下形式的范围:
User.admins
User.moderators
User.authors
    

要回复问题请先登录注册