Ruby on Rails
ActsAsTree

acts_as_tree allows you to traverse a hierarchical structure generated by a self referencing table.

acts_as_tree has been moved to a plugin in Rails 2.0, so it must be installed with:


script/plugin install acts_as_tree

Also see:

API Documentation for acts_as_tree

Database Schema

create table tree_items (
  id int(11) unsigned not null auto_increment,
  parent_id int(11) unsigned,
  name varchar(20),
  other_content varchar(255),
  primary key (id)
);

Code


class TreeItem < ActiveRecord::Base
  acts_as_tree :order=>"name" 
end
Usage


//top level tree item
top = TreeItem.find_by_parent_id(nil)
top.children.each do |child|
  puts child.parent.name + " is my parent. I am " + child.name
end

From code documentation:
The following accessor methods are available with the acts_as_tree modifier:

The following options can be applied to the acts_as_tree modifier: