Many-to-Many Associations

Learn about many-to-many associations in Ecto.

We’re now going to look at a more complex association—many-to-many. These relationships are not as straightforward as belongs_to relationships because we need an extra table to implement them.

Example of a many-to-many relationship

An excellent example of a many-to-many relationship is assigning genres to albums. Genres describe the musical style of an album, such as jazz, classical, rock, blues and so on. We want to be able to assign more than one genre for each album. We also want to associate each genre with more than one album. For example, we’ll have one record in the genres table for jazz, which we want to associate with many different albums.

The traditional way to model this relationship is to create an extra table that maps the relationships between the two other tables. This is called a join table, and usually looks something like this:

Get hands-on with 1200+ tech skills courses.