I mean working with a schema which is actually stored in the database, ie: if you change the Foo.foo
value from “stored_value_in_db” to “new_value”, and later you delete_bar
, when you apply_changes
you lose the current changes. In this case, if you Repo.update(changeset)
the Foo.foo
value won’t be updated. I did something similar to the following to solve this problem (I didn’t try this code):
def handle_event("delete_bar", index, socket) do
bars = Ecto.Changeset.get_change(socket.assigns.changeset, :bars, [])
|> List.delete_at(index)
{:noreply, assign(socket, changeset: Ecto.Changeset.change(bars)}
end
def handle_event("delete_baz", indexes, socket) do
changeset = socket.assigns.changeset
[bar_index, baz_index] = indexes |> String.split("-") |> Enum.map(&String.to_integer/1)
bars = Ecto.Changeset.get_change(socket.assigns.changeset, :bars, [])
|> List.update_at(bar_index, fn bar_ch ->
bazs = Ecto.Changeset.get_change(bar_ch, :bazs, [])
|> List.delete_at(baz_index)
Ecto.Changeset.change(bar_ch, bazs: bazs)
end)
{:noreply, assign(socket, changeset: Ecto.Changeset.change(changeset, bars: bars))}
end
This way I avoid to apply_changes
to don’t lose the changes