Associations

Databases are about tables and the relationships between them. Consider the data model we’ve been working with throughout this course. Artists have many albums, and albums have many tracks and genres. Let’s drill down to the specific relationship between artists and albums.

These two data types reside in separate tables, but they’re closely related. Each album belongs to a particular artist. At the database level, we connect the two tables with a foreign key. In this case, the artist_id column in albums refers to the primary key of the artists table. In Ecto, we use associations to model these relationships. Associations help reflect the connections between database tables in our Elixir code.

This lesson will look at the different types of associations that Ecto supports and how we can add them to our schemas. We’ll then look at how to modify our queries to work with associations and how they can help us insert new records with ease.

One-to-many and one-to-one associations

We created a schema for our albums table to get our first taste of associations. Based on what we learned in the last section, we started it with something like this:

Get hands-on with 1400+ tech skills courses.