Pessimistic Locking

suggest change

lock! reloads the row with SELECT ... FOR UPDATE. Hold that lock inside a transaction. Outside one, the database releases it as soon as the statement finishes, so the later save! is not protected.

appointment = Appointment.find(5)
appointment.with_lock do
  # other transactions can still read the row
  # a second FOR UPDATE, or an UPDATE, waits until this block commits
  appointment.save!
end
# the lock is released when the transaction ends

with_lock opens the transaction, calls lock!, and runs the block. Other sessions are not blocked from ordinary reads.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents