How to make Ecto.Multi link multiple inserts where subsequent inserts require the primary key of the first operation?

:wave:

create_user!(user_params) and create_email!(user, email_params) would need to return {:ok, resource} or {:error, reason}, so these are unlikely to be “bang” operations.

And the last |> Repo.insert() would need to be replaced with Repo.transaction().


@fireproofsocks note that Multi.runs are not automatically rolled back on errors, I’d probably use inserts instead. Modifying @abitdodgy’s example:

alias Ecto.Multi

Multi.new()
|> Multi.insert(:user, User.changeset(%User{}, user_params) end)
|> Multi.insert(:email, fn %{user: %User{id: user_id}} ->
  Email.changeset(%Email{author_id: user_id}, email_params)
end)
|> Repo.transaction()
14 Likes