acts_as_tree.rb 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #---
  2. # Excerpted from "Agile Web Development with Rails",
  3. # published by The Pragmatic Bookshelf.
  4. # Copyrights apply to this code. It may not be used to create training material,
  5. # courses, books, articles, and the like. Contact us if you are in doubt.
  6. # We make no guarantees that this code is fit for any purpose.
  7. # Visit http://www.pragmaticprogrammer.com/titles/rails4 for more book information.
  8. #---
  9. $: << File.dirname(__FILE__)
  10. require "connect"
  11. require "logger"
  12. require "rubygems"
  13. require "active_record"
  14. require "./vendor/plugins/acts_as_tree/lib/active_record/acts/tree.rb"
  15. require "./vendor/plugins/acts_as_tree/init"
  16. #ActiveRecord::Base.logger = Logger.new(STDERR)
  17. ActiveRecord::Schema.define do
  18. create_table :categories, :force => true do |t|
  19. t.string :name
  20. t.integer :parent_id
  21. end
  22. end
  23. class Category < ActiveRecord::Base
  24. acts_as_tree :order => "name"
  25. end
  26. root = Category.create(:name => "Books")
  27. fiction = root.children.create(:name => "Fiction")
  28. non_fiction = root.children.create(:name => "Non Fiction")
  29. non_fiction.children.create(:name => "Computers")
  30. non_fiction.children.create(:name => "Science")
  31. non_fiction.children.create(:name => "Art History")
  32. fiction.children.create(:name => "Mystery")
  33. fiction.children.create(:name => "Romance")
  34. fiction.children.create(:name => "Science Fiction")
  35. def display_children(order)
  36. puts order.children.map {|child| child.name }.join(", ")
  37. end
  38. display_children(root) # Fiction, Non Fiction
  39. sub_category = root.children.first
  40. puts sub_category.children.size #=> 3
  41. display_children(sub_category) #=> Mystery, Romance, Science Fiction
  42. non_fiction = root.children.find(:first, :conditions => "name = 'Non Fiction'")
  43. display_children(non_fiction) #=> Art History, Computers, Science
  44. puts non_fiction.parent.name #=> Books