patrickdm

patrickdm

How to use Ecto optimistic_lock with Phoenix generated update action?

Hello,
I’ve been trying to implement Ecto.Changeset.optimistic_lock in a Phoenix application but I’m stuck with the generated controller’s update action.

In iex I have success rising an Ecto.StaleEntryError when I try to update a stale record, (as shown in the documentation):

iex> post = Repo.insert!(%Post{title: "foo"})
%Post{id: 1, title: "foo", lock_version: 1}
iex> valid_change = Post.changeset(:update, post, %{title: "bar"})
iex> stale_change = Post.changeset(:update, post, %{title: "baz"})
iex> Repo.update!(valid_change)
%Post{id: 1, title: "bar", lock_version: 2}
iex> Repo.update!(stale_change)
** (Ecto.StaleEntryError) attempted to update a stale entry

here the two changeset are being generated from the same post struct, and Repo.update raise the expected error.

On the other hand, when the update is performed concurrently in two browser windows, -my understanding is that- the controller’s update action performs a new get_post!(id) and then uses that struct to make the update’s changeset, with the form params; therefore the latest update is always overwriting the first occurring, thus making optimistic_lock useless in this context.

I couldn’t find much help on this issue, and it make me think I’m getting all this wrong.. Thank’s for any help.

First 4 of 4 Posts Switch mode

1player

1player

That’s an interesting question. Disclaimer: I’ve never used optimistic_lock.

Since lock_version is just a regular field, one idea would be to pass, alongside with the ID, the version of the object in the update method and using that version before you apply any changes.

Example, in your form:

<form action="<%= Routes.post_path(@conn, :update, @post) %>" method="POST">
  ...
  <input type="hidden" name="post[lock_version]" value="<%= @post.lock_version %>"> 
</form>

And in your controller:

def update(conn, %{"id" => id, "post" => %{"lock_version" => lock_version}}) do
  post = 
    id
    |> Posts.get_post!()
    |> Map.put(:lock_version, lock_version)

  ...
end

Now you will will get a StaleEntryError if you’re updating an old post.

EDIT: you might want to use hidden_input to generate the hidden field instead of doing it manually

patrickdm

patrickdm

Hello 1player and thank you,

Since lock_version is just a regular field, one idea would be to pass, alongside with the ID, the version of the object in the update method and using that version before you apply any changes [..]

post = 
  id
  |> Posts.get_post!()
  |> Map.put(:lock_version, lock_version)

Oh :astonished:, right, that easy :man_facepalming:

Replacing the validly-updated new :lock_version with the stale one after get_post!(id)… I’m going to try this now, sure it is going to work!

I’ve been stubbornly poking around with attempts to pass the post struct assigned in edit, from the form to the update action, with no success, and I couldn’t think simple again. Thank you for your help!

Kurisu

Kurisu

Hello @patrickdm! I was wondering if you could share your approach to managing the Ecto.StaleEntryError exception within a controller or a live view?

I came across a similar issue discussed in another thread during my research, but unfortunately, it didn’t have any responses. Your insights would be greatly appreciated.

Kurisu

Kurisu

After conducting further research, I believe I’ve found a suitable solution to my question, particularly in relation to LiveView.

Here’s the section I found in the docs: Error and exception handling — Phoenix LiveView v1.2.5

— All posts loaded —

Where Next?

Trending in Questions Top

jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
silverdr
Using Phoenix.LiveView.TagEngine as an EEx.Engine is deprecated! To compile HEEx, use Phoenix.LiveView.TagEngine.compile/2 instead. Sta...
New
saveman71
Hello ! We want new/edit form pages to POST/PUT to their own URL rather than the resources REST defaults (post /things, put /things/:id)...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
michallepicki
I am using Oban and occasionally, shortly after a deployment, a handful of jobs can fail because of dependency on other parts of the syst...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
type1fool
I just stumbled on a newly redesigned elixir-lang.org. :tada: It looks like @Software_Mansion did the work, and I think it is generally a...
New
akoutmos
@hugobarauna and I (Alex Koutmos) have been hard at work on writing a book on Nerves that takes you from simply blinking LEDs to building...
New

We're in Beta

About us Mission Statement