Recommended approach when adding many records to an existing association with Ecto

I’m working on a db update that doesn’t neatly fall into my existing understanding for cast_assoc/put_assoc/insert the associated model. I’m not sure how to best handle the case where you want to add many records to an existing association. This is how I currently understand the various options:

  • Ecto.Changeset.cast_assoc/3
    • Use when the client is updating the entire association at once
  • Ecto.Changeset.put_assoc/3
    • Use when the client is updating the entire association at once
  • Repo.insert
    • Use for inserting a single record
    • Could be looped for each new record but that would incur a severe performance penalty
  • Repo.insert_all
    • Works well with many items but you have to give up the autogenerated values (which you don’t need to with cast_assoc
  • Ecto.Multi
    • Generally used when composing related operations in a single transaction
    • Can work in this use case but you have to dynamically build up the multi and generate names for them and you can’t do this at the changeset level

So you could use cast_assoc but you’d have to add the existing items in the association to the params. I also see that Ecto 3.x has a section on “Partial changes for many-style associations” that may help, but I’d have to manually preload the association to an empty list which feels wrong.

Is there an approach that I’m missing?

1 Like