Search⌘ K
AI Features

Connecting Products to Cart

Explore how to implement a shopping cart in Rails 6 by generating models for line items, carts, and products. Understand the use of belongs_to and has_many associations to link these components, manage dependent objects, and enforce data integrity. This lesson helps you connect products to carts through model relationships, preparing you to build functional e-commerce features.

We'll cover the following...

We’re looking at sessions because we need somewhere to keep our shopping cart. We’ll cover sessions in more depth in a future chapter, but for now, let’s move on to implement the cart.

We’ll keep things simple. A cart contains a set of products. Based on the initial guess at the application data diagram combined with a brief chat with our customer, we can now generate the Rails models and populate the migrations to create the corresponding tables:

depot> bin/rails generate scaffold LineItem product:references cart:belongs_to
depot> bin/rails db:migrate

The database now has a place to store the references among line items, carts, and products. If we look at the generated definition of the LineItem class, we ...