问题
I have following scope for Mongoid model in Rails 3:
class Expert
include Mongoid::Document
referenced_in :category
scope :currently_available, lambda { |category, limit|
limit ||= 5
{
:where => {:category => category, :state => 'available'},
:limit => limit
}
}
category
here is an instance of referenced model:
class Category
include Mongoid::Document
references_many :experts, :inverse_of => :category
When I call the scope as Expert.currently_available(Category.first, 5)
, I got a Criteria object:
ruby-1.9.2-p136 :110 > Expert.currently_available(Category.first, 5)
=> #<Mongoid::Criteria
selector: {:category=>#<Category _id: 4d95ea8773fdea4c47000003, _type: nil, _id: BSON::ObjectId('4d95ea8773fdea4c47000003'), title: "Tax Advisors", price: 5.5>, :state=>"available"},
options: {:limit=>5},
class: Expert,
embedded: false>
Question is: How can I load a collection within this criteria? When I do .to_a
, it says:Cannot serialize an object of class Category into BSON
Category itself is valid BSON obj when picked up directly, but in scope it fails to render referencing obj.
Thanks in advance!
回答1:
This works for me(Mongoid 2.0):
:where => {:category_id => category.id, :state => 'available'}
来源:https://stackoverflow.com/questions/5523582/mongoid-scope-with-referenced-object-as-criteria