Egor Biriukov
Egor Biriukov

Reputation: 679

Ecto.StaleEntryError when updating

Sometimes I get (Ecto.StaleEntryError) attempted to update a stale struct when trying to update record. I haven't found any recipe to avoid this in Ecto's docs, so what should I do to avoid this?

P.S. I'm using PostgreSQL 9.6 via Postgrex, Ecto 2.1.3.

Upvotes: 11

Views: 5922

Answers (2)

v1d3rm3
v1d3rm3

Reputation: 713

Other possibility may occurr if you manipulate multiple Repos and you're bulding tests. In my case, i was writing some tests, and i've accidently selected differents Repos, so it was giving this error.

Upvotes: 0

Steve Pallen
Steve Pallen

Reputation: 4507

Looks like you are fetching a schema from the database and updating it after it has been updated somewhere else in your app. Are you fetching, hanging onto it, and updating later? If so, fetch, change, and update.

Right from the Ecto docs:

When a conflict happens (a record which has been previously fetched is
being updated, but that same record has been modified since it was
fetched), an `Ecto.StaleEntryError` exception is raised.

Upvotes: 17

Related Questions