counters.rb 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 :products, :force => true do |t|
  25. t.string :title
  26. t.text :description
  27. # ...
  28. t.integer :line_items_count, :default => 0
  29. end
  30. create_table :line_items, :force => true do |t|
  31. t.integer :product_id
  32. t.integer :order_id
  33. t.integer :quantity
  34. t.decimal :unit_price, :precision => 8, :scale => 2
  35. end
  36. end
  37. class Product < ActiveRecord::Base
  38. has_many :line_items
  39. end
  40. class LineItem < ActiveRecord::Base
  41. belongs_to :product, :counter_cache => true
  42. end
  43. product = Product.create(:title => "Programming Ruby",
  44. :description => " ... ")
  45. line_item = LineItem.new
  46. line_item.product = product
  47. line_item.save
  48. puts "In memory size = #{product.line_items.size}" #=> 0
  49. puts "Refreshed size = #{product.line_items(:refresh).size}" #=> 1
  50. LineItem.delete_all
  51. Product.delete_all
  52. product = Product.create(:title => "Programming Ruby",
  53. :description => " ... ")
  54. product.line_items.create
  55. puts "In memory size = #{product.line_items.size}" #=> 1
  56. puts "Refreshed size = #{product.line_items(:refresh).size}" #=> 1