...

/

Iteration 3: Creating a Smarter Cart

Iteration 3: Creating a Smarter Cart

Continue to improve the functionality of an existing cart.

Next we need to migrate the data.

We start by creating a migration:

depot> bin/rails generate migration combine_items_in_cart

A live terminal

You can run the above commands by using the following terminal:

Terminal 1
Terminal
Loading...

This time, Rails can’t infer what we’re trying to do, so we can’t rely on the generated change() method. What we need to do instead is to replace this method with separate up() and down() methods. First, here’s the up() method:

Press + to interact
def up
# replace multiple items for a single product in a cart with a
# single item
Cart.all.each do |cart|
# count the number of each product in the cart
sums = cart.line_items.group(:product_id).sum(:quantity)
sums.each do |product_id, quantity|
if quantity > 1
# remove individual items
cart.line_items.where(product_id: product_id).delete_all
# replace with a single item
item = cart.line_items.build(product_id: product_id)
item.quantity = quantity
item.save!
end
end
end
end

This is easily the most extensive code we’ve seen so far. Let’s look at it in small pieces:

  • We start
...