You can also use ActiveRecord::Base#lock! method to lock one
record by id. This may be better if you don’t need to lock every row.
Example:

Account.transactiondo# select * from accounts where ...accounts=Account.where(...)account1=accounts.detect{|account|...}account2=accounts.detect{|account|...}# select * from accounts where id=? for updateaccount1.lock!account2.lock!account1.balance-=100account1.save!account2.balance+=100account2.save!end

You can start a transaction and acquire the lock in one go by calling
with_lock
with a block. The block is called from within a transaction, the object is
already locked. Example:

account=Account.firstaccount.with_lockdo# This block is called within a transaction,# account is already locked.account.balance-=100account.save!end