I have a Rails 4.2, Mongoid 4 project with these models:
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
I want to find all the Customers (aka Companies) that have a branch with name "New York". I would think that this code would work:
branches = Branch.where(name: "New York").map(&:_id)
=> [BSON::ObjectId('54f76cef6272790316390100')]
Customer.where(:branch_ids => branches).entries
However, it always returns an empty array, no matter what I try. In place of branch_ids
, I've also tried branches
, branch
, branches_id
, and others, but to no avail. I've also tried to convert the BSON::ObjectID
to plain string
, but that doesn't work either.
So, basically, how can I search a model based on an array of association ids? Thanks.
If the relations are
Customer has_many :branches
and
Branch belongs_to :customer
,
Then branches collection will have a customer_id
column and not the reverse. So you can do
cust_ids = Branch.where(name: "New York").map(&:customer_id)
Customer.find(cust_ids)
Since you need only the customer ids from the first query, it is advisable to use pluck
cust_ids = Branch.where(name: "New York").pluck(:customer_id)