具有引用对象作为标准的mongoid范围

时间:2011-04-02 13:59:50

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

我在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。

提前致谢!

1 个答案:

答案 0 :(得分:3)

这对我有用(Mongoid 2.0):

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