Work with Associations

So far, all of our changesets have used a single schema. However, we’ll often need to update associated records as well as parent records at the same time. Ecto provides several options for updating associated records, each serving a particular purpose depending on where our data is coming from and how we want it updated. This section will look at how we can insert and update Artist records and associated Album records.

Updating a single associated record

When making changes to child records, the first question is if we want to make changes to an individual child record or if we want to change the entire collection of associated records at once. If we’re working with personal records, it’s usually best to make changes outside of a changeset. As we’ll see shortly, the functions provided by Ecto.Changeset for working with associations are geared toward the collection. For individual records, Ecto has other options.

The Ecto.build_assoc function

For example, the Ecto.build_assoc function is a great choice to add a new record to an association. We give it the name of the parent record as well as the association’s name, and it generates a new child record with the foreign key set to the parent record. Here’s how we might add a new album to our collection of albums by Miles Davis.

Get hands-on with 1400+ tech skills courses.