通过关联 ID 数组进行 Mongoid 搜索

Mongoid Search by Array of Association Id's

我有一个 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

我想找到所有分支机构名称为 "New York" 的客户(又名公司)。我认为这段代码可以工作:

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

但是,无论我怎样尝试,它总是 returns 一个空数组。除了 branch_ids,我还尝试了 branchesbranchbranches_id 等,但都无济于事。我还尝试将 BSON::ObjectID 转换为普通的 string,但这也不起作用。

那么,基本上,我如何根据关联 ID 数组搜索模型?谢谢。

如果关系是

客户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)

您可以这样使用 Symbol#elem_match

Customer.where(:branches.elem_match => { name: "New York" })

并且 Queryable#elem_match 像这样:

Customer.elem_match(branches: { name: "New York" })

这两个查询都会给 return 你 'New York' 个分支机构的客户。