如何使用Mongoid

时间:2017-10-04 10:21:07

标签: ruby-on-rails ruby scope 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的所有用户。

3 个答案:

答案 0 :(得分:1)

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

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

或作为范围:

class User
  embeds_one :profile

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

答案 1 :(得分:0)

这可以节省你的一天 - ))

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

答案 2 :(得分:0)

当您使用 embeds 时,您只能访问A的相关B对象。因此,您需要的是所有B,其中年龄> x不起作用。因此,请转到 has_one belongs_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