1

I have the following code in my controller:

Item.transaction do
  item = JobDistribution.lock(true).find(params[:id])
  item.update_attributes(status: JobDistribution.statuses[:processing])
  respond_to do |format|
    format.json { render :json => "object processing", status: :success }
  end
end

but when I run the code I'm getting the error:

Attempted to update a stale object: Item

I don't understand why, I followed the rails documentation.

bl0b
  • 926
  • 3
  • 13
  • 30
  • From which documentation do you have this? You are trying to override new data with old, while the new is locked. – Robin Nov 04 '15 at 12:07
  • @Robin http://api.rubyonrails.org/classes/ActiveRecord/Locking/Pessimistic.html – bl0b Nov 04 '15 at 12:41
  • Do you have a `lock_version` column? Is it the latest number, when you try to run your transaction? – Robin Nov 04 '15 at 12:56
  • @Robin I do have a lock version column and here is the failing sql query: `UPDATE "items" SET "status" = 1, "updated_at" = '2015-11-04 11:54:36.422768', "lock_version" = 1 WHERE ("items"."id" = 35 AND "items"."lock_version" = 0)` – bl0b Nov 04 '15 at 13:03

1 Answers1

3

lock_version is for optimistic locking, you're also using pessimistic locking with chaining your find from the lock. Rails is getting confused between the two - pick one or the other.

smathy
  • 26,283
  • 5
  • 48
  • 68