Why is put_assoc calling Repo.update on the association?

When I write:

belongs_to(:associate, Associate, foreign_key: :associate_id, on_replace: :nilify)

def do_associate(object, associated) do
  |> put_assoc(:associate, associated)
  |> Repo.update()

I have the impression that Repo.update is called twice, once on the Object, which makes totally sense, but also on Associate, which from my point of view, doesn’t make sense to me, especially because the foreign key is owned by the Object, hence nothing will change in the Associate data.

Any reason for this? By any chance, can I avoid this issue?


The issue is that you’re confused about what put_assoc is for. put_assoc is not a way to simply set the foreign key, it’s entire purpose is to update both together. If all you’re doing is setting the foreign key, then the best way I’ve found to do that is to simply just set the foreign key.

I’ve also at points created a |> link_assoc(:associate, associated) helper which just sets the foreign key, but either way put_assoc and cast_assoc should be thought of as ways to bind an associated record to the changeset to manipulate them together, not as a way to set foreign keys.