-
-
Save StanisLove/a86b8a1e799e9abeb1a80ceafbdb1fa9 to your computer and use it in GitHub Desktop.
Elixir — Inserting Multiple Changesets Into Database - create batch
This file contains 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