Skip to content

Instantly share code, notes, and snippets.

@churcho
Forked from elderbas/class_controller.ex
Created September 16, 2022 12:38
Show Gist options
  • Save churcho/1dc66b2ca5465f929c6451234bd8f87b to your computer and use it in GitHub Desktop.
Save churcho/1dc66b2ca5465f929c6451234bd8f87b 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment