通过关联ID数组搜索Mongoid

时间:2015-03-11 15:55:42

标签: ruby-on-rails mongoid mongoid4

我有一个带有这些模型的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_id和其他人,但无济于事。我还尝试将BSON::ObjectID转换为普通string,但这也不起作用。

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

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

您可以像这样使用Symbol#elem_match

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

Queryable#elem_match就像这样:

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

这两个查询都会让您回报“纽约”的客户。分支。

相关问题