如何使用 Mongoid 声明基于嵌入式模型属性的范围

How to declare a scope based on embedded model attributes with Mongoid

我有一个 User 模型,其中嵌入了 Profile:

# app/models/user.rb
class User
  embeds_one :profile
end

# app/models/profile.rb
class Profile
  embedded_in :user, inverse_of: :profile
  field :age, type: integer
end

现在我想在 User 中声明一个范围,它可以列出 profile.age> 18 的所有用户。

这应该可以节省您的时间 -))

Class B    
 field :age, type:integer
 scope :adults,  -> { where(:age.gt => 18) }  
end

class A
  embed_one :b
  def embed_adults
    b.adults
  end   
end

https://mongoid.github.io/old/en/mongoid/docs/querying.html#scoping

当您使用 embeds 时,您只能访问 A 的关联 B 对象。因此,您的需求,即年龄>x 的所有 B 都不起作用。所以,选择 has_onebelongs_to

A.rb

class A
  has_one :b
  scope :adults, -> { Bar.adults }
end

B.rb

class B
 field :age ,type:integer
 belongs_to :a
 scope :adults, -> { where(:age.gt=> 18)}
end

您可以通过以下方式查询嵌入文档的属性:

User.where(:'profile.age'.gt => 18)

或作为范围:

class User
  embeds_one :profile

  scope :adults, -> { where(:'profile.age'.gt => 18) }
end