tutorials
tutorials copied to clipboard
Simplify Nested model forms with Phoenix LiveView
Thanks for the great article!
I just wanted to give some feedback after implementing my own solution.
I believe the things can be simplified by utilizing the :ignore action on the variant changeset when no id exists.
defp maybe_mark_for_deletion(changeset) do
if get_change(changeset, :delete) do
%{changeset | action: (if changeset.data.id, do: :delete, else: :ignore)}
else
changeset
end
end
This way, the temp_id virtual attribute and the remove-variant action can be removed entirely. The same deletion logic would apply to both new and existing records.
The other thing to note is that I had quite some buggy behavior in live view until I changed
%{changeset | action: :delete}
to:
put_change(changeset, :action, :delete)
Edit: nope, the reason was that I missed :action in cast() in the variant schema :/.
Edit 2, this is what I run:
defp maybe_mark_for_deletion(changeset) do
if get_change(changeset, :delete) do
# %{changeset | action: if(changeset.data.id, do: :delete, else: :ignore)}
changeset |> put_change(:action, if(changeset.data.id, do: :delete, else: :ignore))
else
changeset
end
end