以引用对象为标准的 mongoid 作用域
我在 Rails 3 中有以下 Mongoid 模型范围:
class Expert
include Mongoid::Document
referenced_in :category
scope :currently_available, lambda { |category, limit|
limit ||= 5
{
:where => {:category => category, :state => 'available'},
:limit => limit
}
}
category
这是引用模型的一个实例:
class Category
include Mongoid::Document
references_many :experts, :inverse_of => :category
当我将范围称为 Expert.currently_available(Category.first, 5)
,我得到了一个 Criteria 对象:
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
时,它会显示:无法将 Category 类的对象序列化为 BSON
直接拾取时,Category 本身是有效的 BSON obj,但在范围内无法渲染引用 obj。
提前致谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这对我有用(Mongoid 2.0):
This works for me(Mongoid 2.0):