Running Transactions with Ecto.Multi
The other way to use Repo.transaction is pass in an Ecto.Multi struct, rather than a function. Ecto.Multi allows you to group your database operations into a data structure. When handed to the transaction function, the Multi’s operations run in order, and if any of them fail, all of the others are rolled back.
Let’s take a look at an earlier example where we ran a transaction with an anonymous function:
| artist = %Artist{name: "Johnny Hodges"} |
| Repo.transaction(fn -> |
| Repo.insert!(artist) |
| Repo.insert!(Log.changeset_for_insert(artist)) |
| end) |
Here’s how we can rewrite it using Multi:
| alias Ecto.Multi |
| |
| artist = %Artist{name: ... |
Get Programming Ecto now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.