0

I am trying to implement the Optimistic Locking for Race Condition. For that, I added an extra column lock_version in the Product: Model through migration.

Product: Model's new field:

#  lock_version                       :integer(4)      default(0), not null

When I try to save! Optimistic Locking is working. Records, updated_at and lock_version are getting an update.

However, in the existing source code, we are using updated_all, which does not update the updated_at and lock_version. So optimistic locking is not working. Please suggest, how to implement optimistic for updated_all

Product.where(:id => self.id).update_all(attributes)
      self.attributes = attributes
Neelabh Singh
  • 2,600
  • 12
  • 51
  • 88
  • Are you getting any error messages when you try the current approach? If so, can you post the error logs? – John Baker Sep 30 '18 at 19:26
  • I don't think that you want to use update_all for this. update_all bypasses all callbacks and is normally used when you want to do a bulk insert. In this case you are looking up a single resource by id so `find` would be better with standard `update` – Austio Sep 30 '18 at 19:31
  • @Austio You mean to say should I use `prod= Product.find(:id => self.id) prod.update(attributes)` – Neelabh Singh Sep 30 '18 at 19:40
  • Correct, you also don't need the hash rocket or specifying id `Product.find(self.id).update(attributes)` There are other things you will have to consider like handling when it is not found. – Austio Sep 30 '18 at 20:19
  • @Austio Thanks for reply, then this will support Optimistic Locking – Neelabh Singh Sep 30 '18 at 20:28

1 Answers1

0

We can simply do as.(in case callback is not needed.)

Product.where(:id => self.id, lock_version: params[:lock_version]).update_all('price = 0, lock_version = lock_version + 1')

That will looking for record with match lock_version and updating lock_version.