Update Records with Associations
Learn how to update records with associations.
We'll cover the following...
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.
Press + to interact
artist = Repo.get_by(Artist, name: "Bill Evans")\|> Repo.preload(:albums)IO.inspect Enum.map(artist.albums, &({&1.id, &1.title}))
It’s OK if the ids in your output don’t match the ones shown here, but the titles should be the same. ...