Associations Using Internal Data
Explore how to effectively manage database associations using Ecto.Changeset in Elixir by working with internal data. Understand the differences between put_assoc and build_assoc, handling preloaded associations, and the importance of the :on_replace option for maintaining data integrity and replacing associated records properly.
When we looked at casting and filtering at the beginning of this chapter, we took different approaches depending on whether or not the data we used was generated in our application code or if it came from an external source. We make a similar distinction when working with associations. We’ll start with internal data using Ecto.Changeset.put_assoc, then use Ecto.Changeset.cast_assoc to work with external data.
Before we continue, if you’ve been running these commands on your local setup, you should run the following.
This will get everything back to a pristine state in our music_db application. We’ll run this a few times throughout the rest of the chapter so we can more easily track the changes we make.
We’ll add the album “Miles Ahead” as we did in the previous section, but this time we’ll use the put_assoc function from Ecto.Changeset rather than build_assoc and observe the differences.
The put_assoc function takes a changeset, the association’s name, and the records we want to put into the association. Like many of the functions in Ecto.Changeset, put_assoc takes a changeset as its first parameter and pipes it into the cast and validation stages. We also need to consider a few extra ...