Search⌘ K
AI Features

Update Records with Associations

Explore how to update parent and associated child records in Elixir using Ecto's cast_assoc within changesets. Learn to handle inserts, updates, and orphaned records safely by configuring on_replace options, enabling you to efficiently manage nested data relationships in your database applications.

We just looked at how to work with cast_assoc when we create a new parent record. Let’s now look at what happens when we’re updating an existing record. Before we do, if you’ve been following along on a local setup, let’s reset the database one more time to clean the slate by using mix ecto.reset

Make changes using cast_assoc

Now let’s make some changes to the Artist and Album records for Bill Evans. You should have an Artist record and two Album records if you’ve just reset your database. We can confirm that with the following bit of code.

Elixir
artist = Repo.get_by(Artist, name: "Bill Evans")\
|> Repo.preload(:albums)
IO.inspect Enum.map(artist.albums, &({&1.id, &1.title}))
widget

It’s OK if the ids in your output don’t match the ones shown here, but the titles should be the same.

Now, let’s make some changes to the collection of albums using cast_assoc. ...