Mongoid - querying by referenced document

馋奶兔 提交于 2019-12-07 14:58:51

问题


I have a model named Ad which looks like this:

class Ad
  include Mongoid::Document
  referenced_in :category
end

and Category model:

class Category
  include Mongoid::Document
  referenced_in :domain
  references_many :ads
end

How can I select Ads by domain? I have tried to use Ad.where('category.domain_id' => domain.id) but this does not work.


回答1:


The problem is that MongoDB doesn't have any way of mapping a Category record to an Ad record. All it knows is that an Ad record has a category_id field so 'category.domain_id' will always return nothing. The dot notation inside queries works only for embedded documents, not references (which are still second-class citizens in MongoDB).

So to solve your problem, you'll need 2 queries:

category_ids = Category.where(:domain_id => domain.id).map(&:_id)
Ad.where(:category_id.in => category_ids)


来源:https://stackoverflow.com/questions/4364213/mongoid-querying-by-referenced-document

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