Skip to content

Instantly share code, notes, and snippets.

@elderbas
Last active April 5, 2024 03:35
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save elderbas/a7928bc21caed63b8c0af26ccc961368 to your computer and use it in GitHub Desktop.
Save elderbas/a7928bc21caed63b8c0af26ccc961368 to your computer and use it in GitHub Desktop.
Elixir — Inserting Multiple Changesets Into Database - create batch
def create_batch(conn, %{"people" => people_params}) do
changesets = Enum.map(people_params, fn class ->
Person.changeset(%Person{}, person)
end)
result = changesets
|> Enum.with_index()
|> Enum.reduce(Ecto.Multi.new(), fn ({changeset, index}, multi) ->
Ecto.Multi.insert(multi, Integer.to_string(index), changeset)
end)
|> Repo.transaction
case result do
{:ok, multi_people_result } ->
render(conn, "index.json", people: Map.values(multi_people_result))
{:error, _, changeset, _ } ->
render(conn, MyApp.ChangesetView, "error.json", changeset: changeset)
end
end
@girorme
Copy link

girorme commented Feb 23, 2024

Nice 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment