$: << File.dirname(__FILE__)
require "connect"
require "logger"
require "rubygems"
require_gem "activerecord"

#ActiveRecord::Base.logger = Logger.new(STDOUT)

#START:model
class Category < ActiveRecord::Base
  acts_as_tree  :order => "name"
end
#END:model

Category.delete_all

#START:setup
root        = Category.create(:name => "Livres")
fiction     = root.children.create(:name => "Fiction")
non_fiction = root.children.create(:name => "Non Fiction")

non_fiction.children.create(:name => "Informatique")
non_fiction.children.create(:name => "Science")
non_fiction.children.create(:name => "Histoire de l'art")

fiction.children.create(:name => "Polar")
fiction.children.create(:name => "Roman")
fiction.children.create(:name => "Science Fiction")
#END:setup

def display_children(order)
  puts order.children.map {|child| child.name }.join(", ")
end

#START:demo
display_children(root)             # Fiction, Non Fiction

sub_category = root.children.first
puts sub_category.children.size    #=> 3
display_children(sub_category)     #=> Polar, Roman, Science Fiction

non_fiction = root.children.find(:first, :conditions => "name = 'Non Fiction'")

display_children(non_fiction)      #=> Histoire de l'art, Informatique, Science
puts non_fiction.parent.name       #=> Livres
#END:demo
