I have a table called OrganisationTrees
which self joins.
Parents are called parent_tree
; children are called sub_trees
. I need to input a single OrganisationTree and then find all of its sub_trees and then all of its sub_trees etc. until all children are exhausted.
My current code is
class OrganisationTree < ActiveRecord::Base
####other code here###
def map_sub_trees(list=[])
unit = []
sub_unit = []
parent = "parent - #{self.name}"
unit << parent
self.sub_trees.each do |tree|
sub_unit<<tree.name
if tree.sub_trees.count >= 1
tree.map_sub_trees(list)
end
end
unit << sub_unit
list << unit
puts list.reverse.inspect
end
And current output looks like this:
[["parent - Tree 1", ["Tree 2", "Tree 4", "Tree 5"]], ["parent - Tree 2", ["Tree 3"]], ["parent - Tree 3", ["Tree 6"]]]
nil
My problem is that I can't seem to get the arrays to nest properly. For example, the array starting parent - Tree 2
should be nested inside array starting parent - Tree 1
as its first element as Tree 2
is the first child of Tree 1.
If it makes life simpler, output could take any form e.g hash