Mongoid - request by reference document

I have a model called Ad that looks like this:

class Ad
  include Mongoid::Document
  referenced_in :category
end

and model category:

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

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

+3
source share
1 answer

The problem is that MongoDB has no way to map record Categoryto record Ad. All he knows is that the record Adhas a field category_id, so it 'category.domain_id'always returns nothing. Dot notation inside queries only works for embedded documents, not links (which are still second-class citizens in MongoDB).

, , 2 :

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

Source: https://habr.com/ru/post/1778688/


All Articles