Ryan K
Ryan K

Reputation: 4053

Mongoid Search by Array of Association Id's

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.

Upvotes: 1

Views: 997

Answers (2)

Sharvy Ahmed
Sharvy Ahmed

Reputation: 7405

You can use Symbol#elem_match like this:

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

And Queryable#elem_match like this:

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

Both query will give return you Customers of 'New York' branches.

Upvotes: 0

Santhosh
Santhosh

Reputation: 29124

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)

Upvotes: 1

Related Questions