Last active
April 5, 2024 03:35
-
-
Save elderbas/a7928bc21caed63b8c0af26ccc961368 to your computer and use it in GitHub Desktop.
Elixir — Inserting Multiple Changesets Into Database - create batch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
Nice 👍