Skip to content
kikito edited this page Dec 3, 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

  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
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.depth} #{n.name}" }
 - a
 - b
 -- c
 --- e
 -- d

Node.arrange_as_array(:order => 'name DESC').each{|n| puts "#{'-' * n.depth} #{n.name}" }
 - b
 - a
 -- d
 -- c
 --- e