如何基于嵌入式模型申报范围与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
。
您可以通过查询嵌入文档的属性:
User.where(:'profile.age'.gt => 18)
或作为范围:
class User
embeds_one :profile
scope :adults, -> { where(:'profile.age'.gt => 18) }
end
非常感谢@stefan这种方式更适合我。我想这earlier.I觉得我在那说明谢谢你为我节省大量的时间做了一个语法错误。 – manojchowdary27
你可以请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
我尝试了,但它示出了用于类未定义的方法或变量b甲 – manojchowdary27
而B.all为零。这可能是因为只有一个集合A并且它嵌入了B.在mongodb中没有这样的集合B – manojchowdary27
当您使用嵌入ü只能访问相关于是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
对不起,无法将关联更改为has_one.Because两个模型都使用单个mongo集合。所以我应该只使用embeds_one关联。 非常感谢乌拉圭回合的答复 – manojchowdary27
不要ü要在范围或全部去取的唯一相关B的? – krishnar
你写的第一件事embeds_one这意味着A将只有一个B,那么为什么年龄> 18?其次:如果你想不管的的获取所有B,则不要使用embeds_one – krishnar
令用户是和Profile是B和剖面模型包含年龄字段 我想获取所有的年龄大于18 – manojchowdary27