thojanssens1

thojanssens1

From `Repo.insert/2` to `Repo.transaction/2`

I have to convert the following code using Repo.insert/2

def create_question(attrs) do
  %Question{}
  |> Question.creation_changeset(attrs)
  |> Repo.insert()
end

to use a transaction:

def create_question(attrs) do
  question_changeset =
    Question.creation_changeset(%Question{}, attrs)

  Multi.new()
  |> Multi.insert(:question, question_changeset)
  |> Multi.run(:do_something, fn _repo, %{question: question} ->
    # do something
    {:ok, nil}
  end)
  |> Repo.transaction()
end

The problem is that now I have to change the code of my controller because the return value of Repo.transaction/2 is different than the return value of Repo.insert/2.

The controller’s action code is the following:

def create(conn, %{"question" => question_params}) do
  case Quiz.create_question(question_params) do
    {:ok, question} ->
      conn
      |> put_flash(:info, "Question created successfully.")
      |> redirect(to: Routes.admin_question_path(conn, :show, question))

    {:error, %Ecto.Changeset{} = changeset} ->
      render(conn, "new.html", changeset: changeset)
  end
end

I think it’s wrong to change controller’s code whether I use a transaction or not? I think that the controller always either needs a struct or a changeset to display the errors, just as Repo.insert/2 returns?

Any advice is welcome on how to refactor that properly, on where I have to change code.

Marked As Solved

idi527

idi527

:waving_hand:

If you don’t need the full result including :do_something, then you can return the same tagged tuple as before:

def create_question(attrs) do
  question_changeset =
    Question.creation_changeset(%Question{}, attrs)

  Multi.new()
  |> Multi.insert(:question, question_changeset)
  |> Multi.run(:do_something, fn _repo, %{question: question} ->
    # do something
    {:ok, nil}
  end)
  |> Repo.transaction()
  |> case do
    {:ok, %{question: question}} -> {:ok, question}
    {:error, :question, %Ecto.Changeset{} = changeset, _changes} -> {:error, changeset}
  end
end

Also Liked

LostKobrakai

LostKobrakai

You want to change the behavior of the function, but not change the values returned? You could manually add an error (and action) to question_changeset if you really want to. Just be aware that you might encounter errors, which are not really related to the form itself and therefore don’t fit that option.

LostKobrakai

LostKobrakai

How about {:error, :upload_failed}. Changesets are very good in folding error messages for fields, which in your case might work out as well, but they don’t have means of holding error messages, which are not specific to a certain field in the form.

LostKobrakai

LostKobrakai

There’s two parts to that. The public api of the context function and whatever is calling it (the controller in your case). The API of your context should return whatever you feel is needed to describe what happened. The controllers job is then to convert the result into stuff on the rendered website, which informs the user. Error tuples is one potential result your context function could have. If a caller is supposed to handle an error you’d not want to use raise.

Where Next?

Popular in Questions Top

chokchit
** (DBConnection.ConnectionError) connection not available and request was dropped from queue after 2733ms. You can configure how long re...
New
New
Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&query=perfume&page=2, I would like to get: ...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
JulienCorb
I am trying to implement my new.html.eex file to create new posts on my website. new.html.eex: <h1>Create Post</h1> <%= ...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: The documentation above suggests that while ...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
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
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
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

Other popular topics Top

hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a > b) do {:ok, "a"} end if (a < b) do {:ok, b} end if (a == b) do {:ok, "equa...
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
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
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
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
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
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement