Pessimistic Locking
suggest changelock! 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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents