20110211000005_combine_items_in_cart.rb 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. class CombineItemsInCart < ActiveRecord::Migration
  18. def self.up
  19. # replace multiple items for a single product in a cart with a single item
  20. Cart.all.each do |cart|
  21. # count the number of each product in the cart
  22. sums = cart.line_items.group(:product_id).sum(:quantity)
  23. sums.each do |product_id, quantity|
  24. if quantity > 1
  25. # remove individual items
  26. cart.line_items.where(:product_id=>product_id).delete_all
  27. # replace with a single item
  28. cart.line_items.create(:product_id=>product_id, :quantity=>quantity)
  29. end
  30. end
  31. end
  32. end
  33. def self.down
  34. # split items with quantity>1 into multiple items
  35. LineItem.where("quantity>1").each do |line_item|
  36. # add individual items
  37. line_item.quantity.times do
  38. LineItem.create :cart_id=>line_item.cart_id,
  39. :product_id=>line_item.product_id, :quantity=>1
  40. end
  41. # remove original item
  42. line_item.destroy
  43. end
  44. end
  45. end