Skip to content

RoR: acts_as_versioned

I’m jump-starting this new blog by copying over the one tech post I have from my personal site. Enjoy!

acts_as_versioned is pretty awesome..but it lacks documentation regarding how it interacts with optimistic locking.

If you have a column named lock_version, then ActiveRecord will use optimistic locking. (yay!) But it also means that acts_as_versioned will not automatically create the version column that it uses, nor will it use it even if you create it yourself. Instead, you need to tell it to use the lock_version column instead:

class Message < ActiveRecord::Base
    validates_uniqueness_of :register_name
 
    acts_as_versioned :version_column => :lock_version
end

Update

Some feedback from Eric Harris-Braun:

Thanks Jason, but be warned there are more issues too. Namely that the version numbers so created will not necessarily be sequential, especially if you have set some :if_changed conditions. This is because the lock_version will be updated even if you don’t make a change, but the version in the your_model_version won’t be saved.

Which is a very good point, only do this if your code can handle non-consecutive version numbers!

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*