markdev

markdev

Using result of intermediate insert in transaction with Ecto Multi

Using Ecto v2.2.6, Phoenix 1.3

I have a blog app. When a user makes a Post, it inserts into the Post table, then it get the resulting id of that post and inserts that into a Newsfeeditem table. Ideally, I would like for this to happen as a transaction.

(I am using Absinthe graphql, so my return for the insert must be of the form {:ok, post})

I have a working function that looks like this:

  def create_post_add_newsfeed(%{
      title: title,
      content: content,
      user_id: user_id
    }) do

    case Repo.insert!(%Post{title: title, content: content, user_id: user_id}) do
      post ->
        case Repo.insert!(%Newsfeeditem{type: "user_creates_post", user_id: user_id, post_id: post.id}) do
          newsfeeditem ->
            {:ok, post}
          _ ->
            {:error, "Post not recorded in newsfeed"}
        end
      _ ->
      {:error, "Post not inserted"}
    end
  end

This code is not a transaction, and it reeks of callback stink. Ecto.Multi seems like a more appropriate tool to use here, but I do not know how to get the result of the Post insert so that I can insert it into Newsfeed.

I would like to do something like this

  def create_post_add_newsfeed(%{
      title: title,
      content: content,
      user_id: user_id
    }) do
    multi =
      Multi.new
        |> Multi.insert(:post, %Post{title: title, content: content, user_id: user_id})
        |> # Some intermediate step where I get the 'post' from the line above
        |> Multi.insert(:newsfeeditem, %Newsfeeditem{type: "user_creates_post", user_id: users_id, post_id: post.id})

    case Repo.transaction(multi) do
      {:ok, %{post: post}} ->
        {:ok, post}
      {:error, _} ->
        {:error, "Error"}
    end
  end

Any idea how to pull that off?

Marked As Solved

cmkarlsson

cmkarlsson

Yes, the Repo.update will update the database outside the transaction. The Multi.update/4 takes a changeset.

You could create a new function:

def post_changeset(%Post{} = post, attrs) do
    post
    |> Post.changeset(attrs)

and use this in the Multi transaction.

Multi.new
|> Multi.update(:post, post_changeset(post, %{content: "Content"})
|> Multi.insert(...)
...

NOTE: Has not been tested :slight_smile:

Also Liked

cmkarlsson

cmkarlsson

Have a look at https://hexdocs.pm/ecto/Ecto.Multi.html#run/3

This function receives the result of the previous Multi step as an argument. In this case you’d return the inserted Post from the step and intercept it.

The “whats-new-in-ecto-2.0.1” ebook contains a section doing just this (Composable transactions with Ecto.Multi) (http://pages.plataformatec.com.br/ebook-whats-new-in-ecto-2-0)

SZJX

SZJX

In my case I needed to follow the initial insertion with an insert_all operation. Multi.merge helped.

cmkarlsson

cmkarlsson

What does update_post function do? Is it possible that this one updates the database outside of the multi transaction? If so that would explain what you are seeing.

markdev

markdev

Got it. This is what worked:

|> Multi.update(:post, Post.changeset(post, %{content: content}))

Where Next?

Popular in Questions Top

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
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
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
hpopp
To simplify some tasks at work, I wrote and published this package yesterday. It’s a simple macro that enables Access behaviour on struct...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> someth...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New

Other popular topics Top

peerreynders
Manning 2016 Halloween weekend sale via Deal of the Day Friday, October 28 - Half off all MEAPs - code WM102816LT Saturday, October 29 ...
326 29600 154
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement