1

私はモンゴイドクエリで少し迷っています。1 つの会社を持つユーザーがいます。モデルはこちら

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

しかし、すべてのユーザーを返す運がありません。

誰かがこのクエリを手伝ってくれますか?

前もって感謝します。

4

1 に答える 1

0

mongoid では、foreign fieldは常に関連付けの側にありbelongs_toます。したがって、Companyオブジェクトにはuser_idフィールドがありますが、Userオブジェクトにはフィールドがありませんcompany_id。したがって、クエリがすべてのユーザーを返すのは「正常」です

mongodb には結合の概念がないため、関連付けを逆にすることでこれを実現できます (ユーザーは会社に属し、会社はユーザーが 1 人いる)、または次の 2 つのクエリを実行できます。

# 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})

于 2012-09-25T16:16:44.330 に答える