Many-to-Many Relationships: Part Two
What This Tutorial Covers
Has Many Through
The modern Rails many-to-many pattern.
Join Models
Models that connect two related models with extra data.
Querying Relationships
Navigate associations through the join model.
Noble Desktop's Full-Stack Web Development Certificate teaches modern web development concepts that transfer across Ruby, Python, and JavaScript stacks.
This tutorial guides you through the process of creating a has_many, through relationship using Ruby on Rails, with an emphasis on setting quantity and the agile development approach.
So here, what we’re going to do is create another model and call it line_item. As shown in the diagram below, the line_item model will be used to connect the products to the carts. This type of relationship is called has_many, through. We’re going to say product has_many :carts through line_items. That way, we have a full-fledged model in between the ends of the many-to-many relationship. The quantity field can be a property of that line_item model.
No longer a mere join table, our Line Item will become an important player on the Rails stage.

If you completed the previous exercises, you can skip the following sidebar. We recommend you finish the previous exercises (8A–9A) before starting this one. If you haven’t finished them, do the following sidebar.
If You Did Not Do the Previous Exercises (8A–9A)
- Close any files you may have open.
- Open the Finder and navigate to Class Files > yourname-Rails Class
- Open Terminal.
- Type
cdand a single space (do NOT press Return yet). - Drag the yourname-Rails Class folder from the Finder to the Terminal window and press ENTER.
- Run
rm -rf nuttyto delete your copy of the nutty site. - Run
Git clone https://bitbucket.org/Noble Desktop/nutty.Gitto copy the That Nutty Guy Git repository. - Type
cd nuttyto enter the new directory. - Type
Git checkout 9Ato bring the site up to the end of the previous exercise. - Run
bundleto install any necessary gems. - Run
yarn install—check-filesto install JavaScript dependencies.