I have these relationships:
class User
include Mongoid::Document
has_many :orders, :class_name => 'Order', :inverse_of => :user
has_many :sold_orders, :class_name => 'Order', :inverse_of => :seller
end
class Order
include Mongoid::Document
belongs_to :user, :class_name => 'User', :inverse_of => :orders
belongs_to :seller, :class_name => 'User', :inverse_of => :sold_orders
end
If I want get all orders for current seller I run in my controller something like:
def jobs
@orders = Order.where(seller: current_user)
p @orders
respond_to do |format|
format.html { render :layout => 'centered'}
end
end
I can see in my log console:
#<Mongoid::Criteria
selector: {:seller=>#<User _id: 500541f81d41c82f1b000037, _type: "User", created_at: 2012-07-17 10:44:08 UTC, ....more attributes>},
options: {},
class: Order,
embedded: false>
This is wrong because I get a user, but I want get all orders for current seller.
How can I get all orders for current seller?
Thank you!
This is totally fine. What you see in console is a Mongoid::Criteria object. Mongoid is very lazy to hit the database and does it only when it absolutely needs to. So instead of accessing the databse here
it only keeps the proxy object and will load the orders when you try to do something on that data. So in order to get your orders in console you may do this:
Moreover, Mongoid does not support
.where(seller: current_user). You need to create your query based on ids for relations so you should build your query like this:Another thing is – you have relations defined so I would use them instead of creating the query yourself so instead of
you can use
and you don’t have to worry if you need to use
sellerorseller_id