More Rails Hacking

Watching the Rails timeline has become a bit of a hobby of mine. You can see all the interesting new features as they’re added, see ideas form and patches take shape. If you’ve been watching the timeline, you may have seen my latest contribution optimistic locking for Active Record. If our table contains a column called ‘lock_version’ you get the locking for free. With locking enabled you get the following behaviour:

p1 = Person.find(1) p2 = Person.find(1) p1.first_name = “Michael” p1.save p2.first_name = “will fail” p2.save # Raises an ActiveRecord::StaleObjectError

It’s similar in effect to Hibernate's version option, the lock_version column gets incremented with every UPDATE and also included in the WHERE clause. This means calling ‘save’ on old references will fail.

While optimistic locking like this isn’t the solution to every concurrency problem under the sun, it is a nice, simple solution to a decent proportion of them.

Posted on January 4th, 2005 | Commenting Closed

Sponsors

Hosted excellently by RailsMachine