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, 我也尝试过branches, branch, branches_id, 和其他的,但无济于事。我也尝试将转换BSON::ObjectID为普通string,但这也不起作用。

那么,基本上,我如何根据关联 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 回答
0

你可以Symbol#elem_match这样使用:

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

像这样Queryable#elem_match

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

这两个查询都会为您返回“纽约”分支机构的客户。

于 2015-03-11T17:27:41.867 回答