one_to_one.rb 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. require "rubygems"
  22. require "active_record"
  23. ActiveRecord::Schema.define do
  24. create_table :invoices, :force => true do |t|
  25. t.integer :order_id
  26. end
  27. create_table :orders, :force => true do |t|
  28. t.string :name
  29. t.string :email
  30. t.text :address
  31. t.string :pay_type
  32. t.datetime :shipped_at
  33. end
  34. end
  35. class Order < ActiveRecord::Base
  36. has_one :invoice
  37. end
  38. class Invoice < ActiveRecord::Base
  39. belongs_to :order
  40. end
  41. Order.create(:name => "Dave", :email => "dave@xxx",
  42. :address => "123 Main St", :pay_type => "credit",
  43. :shipped_at => Time.now)
  44. order = Order.find(1)
  45. p order.invoice
  46. invoice = Invoice.new
  47. if invoice.save
  48. order.invoice = invoice
  49. else
  50. fail invoice.errors.to_s
  51. end
  52. p order.invoice
  53. o = Order.new
  54. p o.id
  55. invoice.order = o
  56. p o.id
  57. invoice.save
  58. p o.id