0

I know Mongoid 4 is still in beta and maybe I've found a bug, but I'm having a hard time understanding why the first query works and the second one returns nothing:

Product.or({sender_uid: params[:user_id]}, {receiver_uid: params[:user_id]})
Product.where({sender_uid: params[:user_id]}).or({receiver_uid: params[:user_id]})

It sort of making it hard to compose any complex queries, so any pointers would be appreciated.

Graham
  • 463
  • 1
  • 5
  • 12

1 Answers1

0

See the following example:

Product 1: sender_uid = 1, receiver_uid = 2
Product 2: sender_uid = 2, receiver_uid = 1
Product 3: sender_uid = 1, receiver_uid = 2

params[:user_id] = 1

In the first query what you are getting is ALL the products where the sender_uid OR the receiver_uid is equal to 1. That is Product 1, 2 and 3.

In the second query you are querying all products where the sender_uid is 1. That is Product 1 and Product 3 and then (on that criteria), the products with receiver_id = 1. Neither the Product 1, not the Product 2 have a receiver with uid 1. So, that's why you're getting nothing. What you are doing in the second query is something like:

Product.where(sender_uid: params[:user_id]).where(receiver_uid: params[:user_id])

UPDATE:

Answering to a comment:

Product.or({ product_id: 1 }, { product_id: 2, sender_uid: 2 })

As you can see, the or method receive to Hashes of conditions. Each one is like a where query.

cortex
  • 5,036
  • 3
  • 31
  • 41
  • That makes sense. I guess I was misunderstanding exactly what the .or and .and methods do (i.e. adding a completely new criteria instead of modifying the existing criteria). If that's the case, how would one implement a more complex query like the following: product_id = 1 OR (product_id = 2 AND sender_uid = 2)? – Graham Mar 27 '14 at 21:04