Iteration 3: Creating a Smarter Cart
Continue to improve the functionality of an existing cart.
We'll cover the following...
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:
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 itemCart.all.each do |cart|# count the number of each product in the cartsums = cart.line_items.group(:product_id).sum(:quantity)sums.each do |product_id, quantity|if quantity > 1# remove individual itemscart.line_items.where(product_id: product_id).delete_all# replace with a single itemitem = cart.line_items.build(product_id: product_id)item.quantity = quantityitem.save!endendendend
This is easily the most extensive code we’ve seen so far. Let’s look at it in small pieces:
- We start