Mongoid查询相关集合

Mongoid Query Related Collection

我正在尝试弄清楚如何在 Mongoid 中查询相关集合。

这是我的对象模型(为简洁起见进行了简化):

Category
-------------------
class Category
    include Mongoid::Document

    field :name, type: String
    ...
    belongs_to: product
end

class Product
   include Mongoid::Document

   field :name, type: String
   ...
   has_one :category
end

我正在尝试构建查询以获取具有特定名称的类别的所有产品,例如"Toy"

products = Product.where('category.name' => 'Toy')

我得到了一个零集合。我认为 mongoid 不直接支持这种类型的查询。我如何构建一个查询来完成它?

尝试以下方法

category = Category.find_by(name: 'Toy')
# all the following will work
products = Product.where(category: category)
products = Product.where(category_id: category.id)

这会起作用,but it's not recommended to use mongoid this way

Mongoid provides relational-style associations as a convenience for application developers who are used to dealing with relational databases, but we do not recommend you use these extensively.