how to make a Recursive function in rails,that will return all CHILDREN of a parent,and children of all CHILDREN AND SO ON....TO N-LEVELS
ruby-on-rails
Solution
Here is some sample (it is not tested! But it will give you some clue):
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 recursion that will try to find all children (nested too) from parent. I know that it is very ugly and unefficient, but I hope ii will give you a clue about finding nested elements.
Problem
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 ```