Associations Using External Data

Learn how associations work with changesets using external data.

We’ll now look at how to create a changeset with associations when the data comes from an external source. We will use the following:

  • Forms presented to the user
  • Uploaded spreadsheet
  • Data posted to an API endpoint and so on

Earlier, we saw that we create new changesets using change or cast, depending on where the data came from. Similarly, we use put_assoc for internal data (as we saw in the last section) or cast_assoc for external data. This section will look at cast_assoc in more depth.

Creating new Records with associations

Let’s start with the case of adding a new parent record with new child records. As we did when we learned about the cast, we’ll assume that the raw data is coming to us as a map of strings. If you’ve been following along on your local setup, reset your data so the previous experiments are wiped away by using mix ecto.reset.

To cast the association into a changeset, Ecto expects the map to have a key matching the association name—the value should contain the values for the child records. For a has_many association, which we’re using here, the value should be a list of maps, with one map per record. For has_one or belongs_to, the value would be a single map.

The cast_assoc works similarly to put_assoc. It takes a changeset and the name of the association to cast.

Let’s create a map of values, set up a new changeset that casts the association, then peek at the changes.

Get hands-on with 1200+ tech skills courses.