mongoid其中和关联值为零

时间:2012-09-24 22:52:35

标签: mongodb mongoid

我对mongoid查询有点失落。我有一个拥有一家公司的用户。 这是模型

class Company
    include Mongoid::Document
    include Mongoid::Timestamps

    field :name,                        :type => String
    field :description,         :type => String
    field :order_minimun,       :type => Float

    belongs_to :user

  def candidate_users
    User.where(:company_id => nil)
  end

end

class User
  include Mongoid::Document
    include Mongoid::Timestamps

    ROLES = %w[admin company_owner customer]

  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :omniauthable

  ## Database authenticatable
  field :email,              :type => String, :default => ""
  field :encrypted_password, :type => String, :default => ""

  validates_presence_of :email
  validates_presence_of :encrypted_password

  ## Recoverable
  field :reset_password_token,   :type => String
  field :reset_password_sent_at, :type => Time

  ## Rememberable
  field :remember_created_at, :type => Time

  ## Trackable
  field :sign_in_count,      :type => Integer, :default => 0
  field :current_sign_in_at, :type => Time
  field :last_sign_in_at,    :type => Time
  field :current_sign_in_ip, :type => String
  field :last_sign_in_ip,    :type => String

    field :name,               :type => String
    field :last_name,          :type => String
    validates_presence_of :name
    #validates_uniqueness_of :name, :email, :case_sensitive => false

    field :roles_list,                  :type => Array , :default => ['customer']
    validates_uniqueness_of :email, :case_sensitive => false

    has_one :company
end

我想列出没有公司的用户以及拥有公司实例的用户。

我的第一次尝试(只是没有公司的用户):

  def candidate_users
    User.where(:company_id => nil)
  end
像这样的事情

def candidate_users
    User.any_of(:company_id => self.id, :company_id => nil)
  end

但是我没有运气,它会让所有用户回归。

有人可以帮助解决此问题吗?

提前致谢。

1 个答案:

答案 0 :(得分:0)

使用mongoid,foreign field始终位于belongs_to关联的一侧。因此Company个对象将包含user_id字段,但User个对象不会有company_id字段。因此,查询返回所有用户是“正常的”

由于mongodb中没有联接的概念,您可以通过撤消关联(用户belongs_to公司,公司has_one用户)或者您可以执行两个查询来实现此目的:

# First, finding ids of users that have a company
ids = Company.excludes(user_id: nil).only(:_id).map(&:id)

# Then, find users whose ids are not in that array
users = User.not_in(_id: ids)

仍然保留关于any_of的部分:

any_of正在对所有哈希参数执行$or查询。通过执行User.any_of(:company_id => self.id, :company_id => nil),您只提供与User.where(:company_id => self.id, :company_id => nil)相同的数组。我认为你想做的是User.any_of({:company_id => self.id}, {:company_id => nil})