2

Using Mongoid, I have an Order class and a LineItem class. The Order class embeds_many line_items. The standard functionality is working fine. However, searching the embedded Line Items doesn't always seem to work. For example, the LineItem class has an "account_id" field. In an attempt to find all Orders that contain at least 1 Line Item with a nil account_id field, I attempt this:

Order.where('line_items.account_id' => nil)

This returns me 2 orders that do, in fact, contain Line Items with nil account_ids. Both orders contain multiple line items, and in both orders some of the line items have account_ids, so this seems to work as expected.

HOWEVER

I happened to discover that there are actually 4 orders within our system that contain line items with nil account_ids. I verified this using something like this:

Order.all.each do |o|
  puts o._id if o.line_items.where(account_id: nil).count > 0
end

This prints out 4 order IDs. I've gone into each one of those 4 and verified that each one does, in fact, contain a line item with an account_id set to nil. So, why doesn't the first search work? Why is the first search only returning 2 orders instead of 4?

After doing some digging, I discovered that, in the 2 orders that are returned by the first query, the first line item in each Order has a nil account_id. In the other 2 orders that contain line items with nil account_ids but are NOT returned by the first query, the first line item in both of those 2 orders does not have a nil account_id, so I'm wondering if the first search I used is only actually searching the first of the many embedded Line Items for each order.

Is this a Mongoid bug? Or am I doing something wrong here? I have to assume I'm doing something wrong, but I can't find any indication of what that might be.

4

0 回答 0