Put_assoc vs. put_change in has_many association

So far I’ve been using put_assoc/4 when adding associated “structs” to a changeset on record creation. Something like

Ecto.Changeset.put_assoc(:comments, [%Comment{body: "example"}])

but stumbled recently across a piece of code that does virtually the same, only using put_change/3 instead and seems to be happy with this. Wondering what are the [potential?] implications of using one over another?

put_assoc and put_change share most of their implementation, though the first does a few more things in terms of validating that the field is actually a assoc or embed. I’d suggest using the intended API, as there’s unlikely a benefit to not doing so.


Roger. Was wondering why would one choose put_change in the first place. Like if there are any non-negligible benefits to using it. Judging from your response it might only have sense in case something wouldn’t pass validations imposed by put_assoc… hm, although that probably wouldn’t work correctly in the end. So I don’t know why somebody used put_change there. I’ll stick to the “intended API” as you suggested :slight_smile: