Making ActiveRecord optimistic locking work together with multi-model forms
I’m a big fan of the lock_version “magic” field in Rails that provides optimistic locking (for almost 0 cost to the programmer). However recently I’ve been having problems with optimistic locking on forms that contain multiple models (I’ve been doing this in Hobo, but you could equally achieve the same thing with something similar to the Complex Forms RailsCast). Every time I tried to update an associated model through my multi-model form ActiveRecord would throw a StaleObjectError, even when I was in development mode on my own machine. Looking into the logs I could see that my app was first deleting the updated associated model, and then trying to perform the update *after* deleting it! This was failing horribly, made no sense and was confusing the hell out of me as to why it was doing something so strange.
After trying to recreate the problem in a toy application I realised that it was being caused by implementing the Comparable mixin in the model that had the problem. However, after a little googling I discovered that ActiveRecord already supports Comparable, and including it in my model seemed to be overwriting something that ActiveRecord was relying on during updates.
Remove include Comparable from your ActiveRecord models.