1

これらのモデルを使用した Rails 4.2、Mongoid 4 プロジェクトがあります。

class Customer #aka Company
  include Mongoid::Document

  has_many :branches
end

class Branch
  include Mongoid::Document  

  field :name, type: String, default: ""

  belongs_to :customer
end

「ニューヨーク」という名前の支店を持つすべての顧客 (別名会社) を検索したいと考えています。このコードは機能すると思います:

branches = Branch.where(name: "New York").map(&:_id)
=> [BSON::ObjectId('54f76cef6272790316390100')]
Customer.where(:branch_ids => branches).entries

ただし、何を試しても、常に空の配列が返されます。の代わりに、、、、などbranch_idsも試しましたが、うまくいきませんでした。また、をプレーンに変換しようとしましたが、それも機能しません。branchesbranchbranches_idBSON::ObjectIDstring

では、基本的に、アソシエーション ID の配列に基づいてモデルを検索するにはどうすればよいでしょうか? ありがとう。

4

2 に答える 2

1

関係が

お客様has_many :branches

支店belongs_to :customer,

次に、ブランチコレクションにはcustomer_id列があり、逆ではありません。だからあなたはすることができます

cust_ids = Branch.where(name: "New York").map(&:customer_id)
Customer.find(cust_ids)

最初のクエリからの顧客 ID のみが必要なため、pluck を使用することをお勧めします。

cust_ids = Branch.where(name: "New York").pluck(:customer_id)
于 2015-03-11T16:17:12.280 に答える