EctoNestedChangeset
This is a package for manipulating nested Ecto changesets.
Installation
Add ecto_nested_changeset to your list of dependencies in mix.exs:
def deps do
[
{:ecto_nested_changeset, "~> 1.1.0"}
]
end
This package is tested against the Elixir and OTP versions that are still
supported upstream. Older versions down to the requirement in mix.exs may
still work, but they are not covered by CI and not officially supported.
Usage
The primary use case of this library is the manipulation of Ecto changesets used as a source for dynamic, nested forms in Phoenix LiveView.
category = %Category{
posts: [
%Post{
id: 1,
comments: [
%Comment{body: "potato", id: 1},
%Comment{body: "you", id: 2}
],
title: "must"
},
%Post{comments: [], id: 2, title: "young"}
]
}
category
|> Ecto.Changeset.change()
|> append_at(:posts, %Post{title: "Padawan", comments: []})
|> prepend_at([:posts, 0, :comments], %Comment{body: "ecneitaP"})
|> delete_at([:posts, 0, :comments, 1], mode: {:action, :delete})
|> insert_at([:posts, 1], %Post{title: "have"})
|> append_at([:posts, 2, :comments], %Comment{body: "my"})
|> update_at([:posts, 0, :comments, 0, :body], &String.reverse/1)
|> Ecto.Changeset.apply_changes()
%Category{
posts: [
%Post{
comments: [
%Comment{body: "Patience"},
%Comment{body: "you", id: 2}
],
id: 1,
title: "must"
},
%Post{title: "have"},
%Post{
comments: [%Comment{body: "my"}],
id: 2,
title: "young"
},
%Post{title: "Padawan"}
]
}
Alternatives
Since Ecto 3.10, Ecto.Changeset.cast_assoc/3 and Ecto.Changeset.cast_embed/3
take :sort_param and :drop_param, which add, remove and reorder items from
the form parameters while casting. If that is all you need, you should prefer
those functions.
This library works on a changeset that already exists, rather than on the parameters one is built from. It covers array fields and the cases where you are not casting parameters at all.
Example application
There is an example Phoenix application with a dynamic nested LiveView form in
the /example folder of the repository.
git clone https://github.com/woylie/ecto_nested_changeset.git
cd ecto_nested_changeset/example
mix setup
mix phx.server
Note that Postgres needs to be running to use the application.
You can access the application at http://localhost:4000.
Status
This library is actively maintained, but given its narrow purpose, it will not see frequent updates.