Search code examples
ruby-on-railsactiverecordpessimistic-locking

Pessimistic locking fails


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.


Solution

  • 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.