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:
   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"]


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

Optimistic locking is based on an object version number.

Reading and object should not affect the version number at all.

If you try to update some object, this version number is compared (in sql actually update statement is used for example "update ... where version = 1 and ..." ) and increased on update.

If the comparison fails when trying to update, you get the stale object error. This means that the object was modified by somebody else while you was doing your changes.

To resolve this error you need to load the object again to get the actual version and maybe merge the changes manually (presenting the user some info about it, and let user decide for example).

Need Your Help

caching images on UITableViewCells with AlamofireImages in my Swift app

ios swift uitableview alamofireimage

I'm writing a Swift app that displays photos fetched from server on each cell of my UITableViewController.