author avatar

akshay

Mon Apr 23 2018

In Rails we can do two modes of locking that is 'Optimistic Locking' and 'Pessimistic locking'. 'Optimistic Locking' assumes that a database transaction conflict is very rare to happen and such locked records can still be read (Shared lock). It uses a version number of the record to track the changes. This can be used by adding a lock_version column to the table and then is handled automatically by Rails.
Whereas 'Pessimistic locking' assumes that database transaction conflict is very likely to happen. It locks the record until the transaction is done (Exclusive lock). This can be done with ActiveRecord::Base#lock! or ActiveRecord::Locking::Pessimistic#with_lock.