How to make a recursive function in rails, which will return all CHILDREN of the parent and children of all children, etc .... TO N-LEVELS

I have a method as shown:

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 
+4
source share
2 answers

Here is an example (it has not been verified! But this will give you a hint):

 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 

So this is a recursion that will try to find all the children (nested too) from the parent. I know that it is very ugly and inefficient, but I hope that it will give you the key to finding nested elements.

+3
source

Here is an example. I looked for this reason because I was too lazy to think about it, but since I found it here, I decided to do it right. Here is the code you can use with the standard way to create Rails associations.

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

Note the two uses there of return . If you missed the inside, you will find yourself with only one level of deep tree.

Hooray!

+1
source

All Articles