Thanks, based off your suggestion I’ve written the following:
defmodule Parent do
schema "parents" do
has_one :child, Child, on_replace: :update
end
def changeset(%Parent{} = ch, attrs) do
ch
|> cast(attrs, [])
|> cast_assoc(:child)
|> changeset_preload(:child)
|> put_assoc_nochange(:child, %{})
end
def changeset_preload(ch, field),
do: update_in(ch.data, &Repo.preload(&1, field))
def put_assoc_nochange(ch, field, new_change) do
case get_field(ch, field) do
nil -> put_assoc(ch, field, new_change)
_ -> ch
end
end
end
changeset_preload/2
is based off this post.
Though I’m not sure if this is the best way to solve this problem, I’m pretty ok with the solution. Unfortunately, I have to put a preload for when put_assoc
is called.