我有一个Rails 4.2,Mongoid4项目,其中有以下模型:
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,但这也不起作用。
因此,基本上,如何根据关联ids数组搜索模型?谢谢。
发布于 2015-03-11 16:17:12
如果关系是
客户has_many :branches和
分支belongs_to :customer,
然后分支集合将有一个customer_id列,而不是相反的列。所以你可以
cust_ids = Branch.where(name: "New York").map(&:customer_id)
Customer.find(cust_ids)由于您只需要第一个查询中的客户it,因此建议使用pluck。
cust_ids = Branch.where(name: "New York").pluck(:customer_id)发布于 2015-03-11 17:27:41
您可以这样使用Symbol#elem_match:
Customer.where(:branches.elem_match => { name: "New York" })Queryable#elem_match是这样的:
Customer.elem_match(branches: { name: "New York" })这两个查询都将返回“纽约”分支机构的客户。
https://stackoverflow.com/questions/28991420
复制相似问题