one_to_one.rb 1.3 KB

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