mongoid scope with referenced object as criteria

柔情痞子 提交于 2019-12-24 00:52:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!