以参照物为标准的蒙古范围 [英] mongoid scope with referenced object as criteria
问题描述
在Rails 3中,我对Mongoid模型有以下范围:
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
这是引用模型的一个实例:
category
here is an instance of referenced model:
class Category
include Mongoid::Document
references_many :experts, :inverse_of => :category
当我将范围称为Expert.currently_available(Category.first, 5)
时,我得到了一个Criteria对象:
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>
问题是:如何在此条件下加载收藏集?当我做.to_a
时,它说:
Cannot serialize an object of class Category into BSON
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
直接拾取类别时,类别本身是有效的BSON obj,但在范围上无法呈现引用的obj.
Category itself is valid BSON obj when picked up directly, but in scope it fails to render referencing obj.
提前谢谢!
推荐答案
这对我有用(Mongoid 2.0):
This works for me(Mongoid 2.0):
:where => {:category_id => category.id, :state => 'available'}
这篇关于以参照物为标准的蒙古范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!