Mongoid - querying by referenced document

2019-05-10 16:58发布

问题:

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)