...

/

Solution: Work with Transactions and the Multi Module

Solution: Work with Transactions and the Multi Module

Go over the solution to the "Work with Transactions and the Multi Module" problem.

We'll cover the following...

Solution

We are going to rewrite this code by using Ecto.Multi.

Press + to interact
cs = Ecto.Changeset.change(%Album{title: "Bag's Groove", artist_id: 1})
|> Ecto.Changeset.validate_required([:title])
Repo.transaction(fn ->
case Repo.insert(cs) do
{:ok, _album} -> IO.puts("Album insert succeeded")
{:error, _value} -> Repo.rollback("Album insert failed")
end
case Repo.insert(Log.changeset_for_insert(cs)) do
{:ok, _log} -> IO.puts("Log insert succeeded")
{:error, _value} -> Repo.rollback("Log insert failed")
end
end)

It inserts a new album record as well as a log entry. We used an anonymous function with the ...