2017-10-04 69 views
2

屬性我有一個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

回答

1

您可以通過查詢嵌入文檔的屬性:

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

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

+0

我嘗試了,但它示出了用於類未定義的方法或變量b甲 – manojchowdary27

+0

而B.all爲零。這可能是因爲只有一個集合A並且它嵌入了B.在mongodb中沒有這樣的集合B – manojchowdary27

0

當您使用嵌入ü只能訪問相關於是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