2013-09-22 93 views
2

的兒童假設我有一個grandparent文件有許多parents,每個parent有許多childrenMongoid - 讓孩子

什麼是最好的方式,與Mongoid Rails中,讓所有的children特定grandparent無循環?

例如,如果我使用循環,它會是這個樣子(粗碼):

def children 
    children = [] 
    parents.each do |p| 
     p.children.each do |c| 
     children << c 
     end 
    end 
    children.uniq 
    end 

class Grandparent 
    include Mongoid::Document 
    has_many :parents 
end 

class Parent 
    include Mongoid::Document 
    belongs_to :grandparent 
    has_many :children 
end 

class Child 
    include Mongoid::Document 
    belongs_to :parent 
end 
+0

「最佳」在你的目的方面來界定。你正在優化性能,可讀性,模塊化,還是具體什麼? – Mustafa

+0

@Mustafa表演。 – Baub

回答

0

像這樣的方法,它會載入children因爲一旦稱爲屬性。

def children(reload=false) 
    @children = nil if reload 
    @children ||= Child.where(:parent_id.in => parents.map(&:id)) 
end 

看到這個SO answer以及

+0

這將返回nil:'children = Child.where(:parent_id.in => parents.map(&:id))',但我的問題中的循環示例有效。 – Baub

+0

@James它會幫助,如果你張貼模型文件顯示如何定義關聯。 – tihom

+0

@tihorn添加到原始問題。 – Baub