sti.rb 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. #---
  10. # Excerpted from "Agile Web Development with Rails, 4rd Ed.",
  11. # published by The Pragmatic Bookshelf.
  12. # Copyrights apply to this code. It may not be used to create training material,
  13. # courses, books, articles, and the like. Contact us if you are in doubt.
  14. # We make no guarantees that this code is fit for any purpose.
  15. # Visit http://www.pragmaticprogrammer.com/titles/rails4 for more book information.
  16. #---
  17. $: << File.dirname(__FILE__)
  18. require "connect"
  19. require "logger"
  20. ActiveRecord::Base.logger = Logger.new(STDERR)
  21. ActiveRecord::Schema.define do
  22. create_table :people, :force => true do |t|
  23. t.string :type
  24. # common attributes
  25. t.string :name
  26. t.string :email
  27. # attributes for type=Customer
  28. t.decimal :balance, :precision => 10, :scale => 2
  29. # attributes for type=Employee
  30. t.integer :reports_to
  31. t.integer :dept
  32. # attributes for type=Manager
  33. # -- none --
  34. end
  35. end
  36. class Person < ActiveRecord::Base
  37. end
  38. class Customer < Person
  39. end
  40. class Employee < Person
  41. belongs_to :boss, :class_name => "Manager", :foreign_key => :reports_to
  42. end
  43. class Manager < Employee
  44. end
  45. Customer.create(:name => 'John Doe', :email => "john@doe.com",
  46. :balance => 78.29)
  47. wilma = Manager.create(:name => 'Wilma Flint', :email => "wilma@here.com",
  48. :dept => 23)
  49. Customer.create(:name => 'Bert Public', :email => "b@public.net",
  50. :balance => 12.45)
  51. barney = Employee.new(:name => 'Barney Rub', :email => "barney@here.com",
  52. :dept => 23)
  53. barney.boss = wilma
  54. barney.save!
  55. manager = Person.find_by_name("Wilma Flint")
  56. puts manager.class #=> Manager
  57. puts manager.email #=> wilma@here.com
  58. puts manager.dept #=> 23
  59. customer = Person.find_by_name("Bert Public")
  60. puts customer.class #=> Customer
  61. puts customer.email #=> b@public.net
  62. puts customer.balance #=> 12.45
  63. b = Person.find_by_name("Barney Rub")
  64. p b.boss