forked from stefankroes/ancestry
-
Notifications
You must be signed in to change notification settings - Fork 3
arrange_as_array
kikito edited this page Jun 4, 2012
·
6 revisions
If you want to have your tree in an ordered List accordingly to the tree structure (for example to represent the children in a sorted out list in a select), you can use this snippet:
class Node < ActiveRecord::Base
has_ancestry :cache
def self.arrange_as_array(options={}, hash=nil)
hash ||= arrange(options)
arr = []
hash.each do |node, children|
arr << node
arr += arrange_as_array(options, children) unless children.empty?
end
arr
end
Usage:
a = Node.create(:name => "a")
b = Node.create(:name => "b")
c = Node.create(:name => "c", :parent => b)
d = Node.create(:name => "d", :parent => b)
e = Node.create(:name => "e", :parent => c)
Node.arrange_as_array.each{|n| puts "#{'-' * n.level} #{n.name}" }
- a
- b
-- c
--- e
-- d
Node.arrange_as_array(:order => 'name DESC').each{|n| puts "#{'-' * n.level} #{n.name}" }
- b
- a
-- d
-- c
--- e