2012-07-26 69 views
4

我有一個方法,如下所示:如何在軌遞歸函數,將返回父母的孩子,和所有兒童的兒童等等.... TO N-水平

def all_pages_and_its_n_level_child 

    @parent_pages = Page.where(:parent_id => params[:page_id]) 
    #this will give me all child of this page 
    for page in @parent_pages 
      child_exists=Page.where(:parent_id=>page.id) 
      #this will give all children of that page 
      #*I want to make this loop further so that i can check to N-levels, 
      #this is only for two levels* 
    end 


end 

回答

3

下面是一些示例(這是未經測試,但它會給你一些線索!):

def all_children(children_array = []) 
    children = Page.where(parent_id: self.id) 
    children_array += children.all 
    children.each do |child| 
    child.all_children(children_array) 
    end 
    children_array 
end 

所以這是遞歸,將嘗試找到從父所有的孩子(嵌套過)。我知道這非常醜陋,沒有效率,但我希望ii會給你一些關於尋找嵌套元素的線索。

1

這是一個適當的例子。我搜索了這個原因,我懶得想它,但是因爲我在這裏發現了這個,所以我決定正確地做。以下是您可以使用Rails關聯的默認方式使用的代碼。

def all_children(children_array = []) 
    children_array += self.children 
    children.each do |child| 
     return child.all_children(children_array) 
    end 
    return children_array 
end 

請注意,有回報兩種用法。如果你錯過了裏面的一個,你最終只會得到一層深的樹。

乾杯!