如何基于嵌入式模型申报范围与Mongoid

问题描述:

属性我有一个User模型中嵌入一个Profile如何基于嵌入式模型申报范围与Mongoid

# 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

+0

不要ü要在范围或全部去取的唯一相关B的? – krishnar

+0

你写的第一件事embeds_one这意味着A将只有一个B,那么为什么年龄> 18?其次:如果你想不管的的获取所有B,则不要使用embeds_one – krishnar

+0

令用户是和Profile是B和剖面模型包含年龄字段 我想获取所有的年龄大于18 – manojchowdary27

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

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

或作为范围:

class User 
    embeds_one :profile 

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

非常感谢@stefan这种方式更适合我。我想这earlier.I觉得我在那说明谢谢你为我节省大量的时间做了一个语法错误。 – manojchowdary27

+0

你可以请upvote我的问题too.and再次感谢您的答案 – manojchowdary27

这应该保存你的一天 - ))

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

+0

我尝试了,但它示出了用于类未定义的方法或变量b甲 – manojchowdary27

+0

而B.all为零。这可能是因为只有一个集合A并且它嵌入了B.在mongodb中没有这样的集合B – manojchowdary27

当您使用嵌入ü只能访问相关于是A.说明B对象,你需要即所有B,其中年龄> x不起作用。所以,去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 
+0

对不起,无法将关联更改为has_one.Because两个模型都使用单个mongo集合。所以我应该只使用embeds_one关联。 非常感谢乌拉圭回合的答复 – manojchowdary27