Changing the association of a given child
from parent_a
to parent_b
via parent_id
in params leaves a stale record.parent
object.
e.g. (assume params matches %{child: %{id: '1', parent_id: '6'}}
)
# ...
child = Repo.get(Child, child_id)
|> preload([:parent])
changeset = Child.changeset(child, child_params)
case Repo.update(changeset) do
{:ok, child} ->
IO.puts child.parent_id # returns '6', or the new, changed `id`
IO.puts child.parent.id # returns '5', or the old id
# child.parent is stale
# ...
What is the proper way to retrieve the newly associated parent record after updating?
force: true
toRepo.preload
to force reloading of an already-loaded association. Source: hexdocs.pm/ecto/2.0.0-rc.1/Ecto.Repo.html#c:preload/3 – Amentia