Iteration 3: Creating a Smarter Cart
Understand how to create a smarter cart in Rails by writing custom migrations that combine multiple line items into single entries. Learn to implement reversible up and down migration methods, update your application views, and adjust tests to reflect these changes. Explore best practices for detecting and handling potential security risks related to user input on cart IDs.
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:
This is easily the most extensive code we’ve seen so far. Let’s look at it in small pieces:
- We start by iterating over each cart.
- For each cart, we get a sum of the quantity fields for each of the line items associated with this cart, grouped