Iteration 1: Creating a Smarter Cart
Learn to improve the functionality of an existing cart.
We'll cover the following
Associating a count with each product in our cart is going to require us to modify the line_items
table. We’ve used migrations before, like when we used migration in Applying the Migration, to update the schema of the database. While that was as part of creating the initial scaffolding for a model, the basic approach is the same:
depot> bin/rails generate migration add_quantity_to_line_items quantity:integer
Rails can tell from the name of the migration that we’re adding columns to the line_items
table and can pick up the names and data types for each column from the last argument. The two patterns that Rails match on are AddXYZToTABLE
and RemoveXYZFromTABLE
, where the value of XYZ
is ignored. What matters is the list of column names and types that appear after the migration name.
The only thing Rails can’t tell is what a reasonable default is for this column. In many cases, a null
value would do, but let’s make it the value 1 for existing carts by modifying the migration before we apply it:
Get hands-on with 1400+ tech skills courses.