Last Updated: February 25, 2016
· sheerun

Use optimistic and pessimistic locking for critical models

Thanks Optimistic Locking facility of Active Record, you can easily implement ACID updates on Ruby level. Here's how to do it:

  • Add :lock_version, :integer, default: 0 column to model
  • Use that column in forms for your model
  • Catch and resolve StaleObjectError on your model updates:


def add_cash(purse) += 100!
rescue ActiveRecord::StaleObjectError

If you want to be 300% sure, use additionally transactions and locking records on database level (aka Pessimistic Locking).

Bonus: always use InnoDB instead of MyISAM for real business applications. It deals far better with locks and transactions.