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.
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.