Last Updated: February 25, 2016
·
3.211K
· 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)
  purse.cash += 100
  purse.save!
rescue ActiveRecord::StaleObjectError
  add_cash(purse.reload)
end

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.