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

Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
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
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
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
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
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
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
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New

Other popular topics Top

Qqwy
Update: How to use the Blogs & Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3268 119930 1237
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30048 115
New
AstonJ
You’re a programmer, so you don’t need spoon feeding with the conventional drivel about “this is an integer.” No. You need to know what’s...
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
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
magnetic
Hey :wave:t3: Elixir community, I’ve been learning Elixir, and working on some side projects. My editor of choice is VSCode, and althoug...
New

We're in Beta

About us Mission Statement