20121130000005_combine_items_in_cart.rb 1.4 KB

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