Pessimistic Offline Lock prevents conflicts between concurrent business transactions by allowing only one business transaction at a time to access a particular data object. Example: If Joe edits the record of Customer X, Bill can not get access to edit the record of Customer X until Joe has committed his changes.

Ruby on Rails

Ruby on Rails provides several mechanisms to handle the locking of objects to ensure data consistency and prevent race conditions when multiple processes or users attempt to edit the same object simultaneously. The two primary types of locking mechanisms in Rails are Optimistic Locking and Pessimistic Locking.

Pessimistic Locking is a technique where a record is locked for the duration of a transaction, preventing other processes from modifying it until the lock is released. This is typically done using database-level locks.

How It Works:

  1. Use lock method to lock the record.
  2. The lock is held until the end of the transaction.

Example: Usage: Use the lock method within a transaction to lock the record.

ActiveRecord::Base.transaction do
  article = Article.lock.find(1)
  article.title = "New Title"
  article.save
end

The lock method issues a SELECT ... FOR UPDATE SQL query, which locks the selected rows until the transaction is complete.

Summary

Both mechanisms help ensure data consistency and prevent race conditions when multiple processes or users attempt to edit the same object simultaneously.