Advertisement
Guest User

Simple Migration

a guest
May 30th, 2016
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.04 KB | None | 0 0
  1. class CombineItemsInCart < ActiveRecord::Migration
  2.  
  3.   def up
  4.     # replace multiple items for a single product in a cart with a
  5.     # single item
  6.     Cart.all.each do |cart|
  7.       # count the number of each product in the cart
  8.       sums = cart.line_items.group(:product_id).sum(:quantity)
  9.  
  10.       sums.each do |product_id, quantity|
  11.         if quantity > 1
  12.           # remove individual items
  13.           cart.line_items.where(product_id: product_id).delete_all
  14.  
  15.           # replace with a single item
  16.           item = cart.line_items.build(product_id: product_id)
  17.           item.quantity = quantity
  18.           item.save!
  19.         end
  20.       end
  21.     end
  22.   end
  23.  
  24.   def down
  25.     # split items with quantity>1 into multiple items
  26.     LineItem.where("quantity>1").each do |line_item|
  27.       # add individual items
  28.       line_item.quantity.times do
  29.         LineItem.create cart_id: line_item.cart_id,
  30.           product_id: line_item.product_id, quantity: 1
  31.       end
  32.  
  33.       # remove original item
  34.       line_item.destroy
  35.     end
  36.   end
  37. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement