fireproofsocks

fireproofsocks

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

A fairly simple use-case: a user has one or more email addresses, stored in the database in 2 separate tables (users, emails) such that the emails table has a foreign key for user_id. (In reality, my use case is more complex, but this illustrates the problem).

Ecto.Multi lets us create a single transaction for adding both the user record and an email record, and we can rollback if either one of those operations fail. I’m looking at the docs for the run/3 and run/5 functions https://hexdocs.pm/ecto/Ecto.Multi.html#run/3 but I can’t figure out how these are supposed to be used. From the docs, I’m not at all clear on what value the run function is supposed to return or how that gets ingested by the next operation.

I know I could (sometimes) do this with a single insert operation by leveraging the relationships defined in the schema, but I’m more interested in the principle of the thing.

Thanks as always!

Most Liked

idi527

idi527

: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
Post #3
abitdodgy

abitdodgy

Edit: I’d use @idi527’s example as it’s much more idiomatic.


Here’s a contrived example that should give you the general idea.

Ecto.Multi.new
|> Ecto.Multi.run(:user, fn _ ->
  create_user(user_params)
end)
|> Ecto.Multi.run(:email, fn %{user: user} ->
  create_email(user, email_params)
end)
|> Repo.transaction()

When you use Multi.run, you tag the operation using the second argument. For example, the |> Ecto.Multi.run(:user ... makes the result of create_user available under the :user key in the next the function.

LostKobrakai

LostKobrakai

Are you sure? A Multi is executed in a transaction and for as long as the command in a Multi.run does only cause side effects to the db and nothing else it should just be rolled back like any other db operation, which happened in that transaction. I‘ve even some places in my projects, where Multis are effectively nested, as the inner multis are executed in named functions which a outer multi composes.

LostKobrakai

LostKobrakai

OvermindDL1

OvermindDL1

Precisely, DB actions are rolled back because of a transaction, but run/3,5 is often used to perform non-db actions that need to be run only if the DB succeeds, however there is not version of run/? that allows you to pass both a ‘do’ and an ‘undo’ function, which would be a huge help personally. as right now you have to check it ‘after’ running Repo.transaction, thus meaning the actions of the multi have to ‘leak’ out of where they are defined. We could really use a run/4;8 as well to support both a do and undo…

Where Next?

Popular in Questions Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
gonzofish
I’m currently trying to understand how to join three tables using Ecto. All the examples I’ve seen use 2, so maybe I’m just missing somet...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
Exadra37
Sometimes I want to check if the input into a function is not a blank string. My first approach: defmodule Example do def do_stuff(s...
New
sabri
Can someone explain the settings of pool_size of Ecto in config file? and what is the recommend size? Thanks
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New

Other popular topics Top

shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New

We're in Beta

About us Mission Statement