Learning Goals 🎯

  1. Understand how to relate multiple models to eachother in more complex ways
  2. Be able to create join tables to establish many-to-many relationships
  3. Implement polymorphic associations to have one model belong to multiple different models

Prerequisites 🤔

In the first part of this guide, we are going to be finishing up our discussion of models by briefly discussing join tables, various types of many-to-many relationships, and polymorphic associations.

We are slowly entering the section of the course that is more on-demand knowledge. It's important to know these things are possible and you'll likely find yourself using them a lot, but it's not essential to the core of understanding what Rails is. All of this will become second nature with practice and experience, but for now we want to arm you with the knowledge that these ideas exist so you know where to look next time you encounter them!

What are Many-to-Many relationships?

The issue with databases is that there is no simple way to store an "array" of objects. An Artist model can't hold an array of albums in its table because each cell in the table can only hold primitive datatypes. They can only hold one value.

Last time, we discussed how we can relate models together instead by having each album reference the artist it belongs to. In a database with Albums and Artists, the Album table would have a column named artist_id that references which artist it belongs to. In order to find an Artist's albums, we would have to go through the album table and find all albums that match its artist_id field!

This is a pretty elegant way to solve the issue of both one-to-one (Every artist has one album and every album has one artist) and one-to-many (Every artist has multiple albums but every album has one artist) relationships. What about, however, many-to-many relationships?