sti.rb 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. ActiveRecord::Base.logger = Logger.new(STDERR)
  13. ActiveRecord::Schema.define do
  14. create_table :people, :force => true do |t|
  15. t.string :type
  16. # common attributes
  17. t.string :name
  18. t.string :email
  19. # attributes for type=Customer
  20. t.decimal :balance, :precision => 10, :scale => 2
  21. # attributes for type=Employee
  22. t.integer :reports_to
  23. t.integer :dept
  24. # attributes for type=Manager
  25. # -- none --
  26. end
  27. end
  28. class Person < ActiveRecord::Base
  29. end
  30. class Customer < Person
  31. end
  32. class Employee < Person
  33. belongs_to :boss, :class_name => "Manager", :foreign_key => :reports_to
  34. end
  35. class Manager < Employee
  36. end
  37. Customer.create(:name => 'John Doe', :email => "john@doe.com",
  38. :balance => 78.29)
  39. wilma = Manager.create(:name => 'Wilma Flint', :email => "wilma@here.com",
  40. :dept => 23)
  41. Customer.create(:name => 'Bert Public', :email => "b@public.net",
  42. :balance => 12.45)
  43. barney = Employee.new(:name => 'Barney Rub', :email => "barney@here.com",
  44. :dept => 23)
  45. barney.boss = wilma
  46. barney.save!
  47. manager = Person.find_by_name("Wilma Flint")
  48. puts manager.class #=> Manager
  49. puts manager.email #=> wilma@here.com
  50. puts manager.dept #=> 23
  51. customer = Person.find_by_name("Bert Public")
  52. puts customer.class #=> Customer
  53. puts customer.email #=> b@public.net
  54. puts customer.balance #=> 12.45
  55. b = Person.find_by_name("Barney Rub")
  56. p b.boss