Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Stale object error. Optimistic Locking: How does it work?

I think I've eliminated everything, but I'm not sure I understand OL perfectly enough to be sure. In general, let's say you and I are on a team to keep a foo up to date. I'm in one room and decide to save time I'll update the foo myself. So I start updating it. A minute later you have the same idea and log onto the edit page to update it as well. What happens if I finish first? What happens if you finish first? In a configuration where it fails how does it distinguish between someone editing and someone reading. If I catch and reload to update the lock I lose all my changes, how is this solved? Here, it's simple to redo the update, but potentially it's part of a more complicated form object.

My specific problem came when (best I can make out) loaded one copy in my browser, later forgot about it and then one in my console (also lock: 0?) couldn't update the one in my console with stale object error. Noticed the browser thing. Closed my console. Tried to reload my browser and got stale object error as well. Here's the code that's failing:

=>  7:       self.update_attributes({
    8:         failed_view_attempts: self.failed_view_attempts += 1,
    9:         failed_view_at: Time.now
   10:       })
   11:     end
(byebug) self
#<Product id: 12... lock_version: 0>

#=> ActiveRecord::StaleObjectError (Attempted to update a stale object: Product.)

Things I've tried:

To see if another instance was being loaded I added puts "CALLED !!!!" in an after_initializecallback, but it only printed once.

And checking self.changed after rescuing from the error and get back ["updated_at", "failed_view_attempts", "failed_view_at"]

like image 706
MCB Avatar asked Sep 13 '16 18:09

MCB


People also ask

What is optimistic locking failure?

Error - DB Optimistic Lock Failure: Expected to update 1 row actually updated 0. This error usually happens when you are trying to update a record which is locked by another process. Once you get this error, it will keep on trying and lock up the servers. Once the server is restarted, it should process the request.

What is optimistic locking in rails?

Optimistic locking is a mechanism to prevent data overrides by assuming that a database transaction conflict rarely happens. Optimistic locking uses a "version-number" column to track changes in each table that needs to implement concurrent access.


1 Answers

Need to set lock_version column default to zero (0).

like image 132
MCB Avatar answered Oct 02 '22 20:10

MCB