【问题标题】:mongoid scope with referenced object as criteria以引用对象为标准的 mongoid 范围
【发布时间】:2011-07-28 06:31:16
【问题描述】:

我在 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 时,它会说:
Cannot serialize an object of class Category into BSON

直接拾取时,类别本身是有效的 BSON obj,但在范围内它无法呈现引用 obj。

提前致谢!

【问题讨论】:

  • :where =&gt; {:category =&gt; category._id, :state =&gt; 'available'}, 似乎有效。有人可以确认/纠正我吗?
  • 不幸的是仍然无法让它工作。尝试了通过 category._id 匹配的不同 mongo 运算符 - 它只返回空数组。

标签: ruby-on-rails-3 mongoid bson


【解决方案1】:

这对我有用(Mongoid 2.0):

:where => {:category_id => category.id, :state => 'available'}

【讨论】:

  • .id 是 ._id 的别名。 ruby-1.9.2-p136 :002 &gt; e.id =&gt; BSON::ObjectId('4d9b5c6173fdeab5e6000008') ruby-1.9.2-p136 :003 &gt; e._id =&gt; BSON::ObjectId('4d9b5c6173fdeab5e6000008')
  • 抱歉延迟回复,但这里的关键是使用“category_id”而不是“category”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-20
  • 2012-04-14
  • 2010-10-11
  • 1970-01-01
相关资源
最近更新 更多