method
lock!
v5.1.7 -
Show latest stable
- Class:
ActiveRecord::Locking::Pessimistic
lock!(lock = true)public
Obtain a row lock on this record. Reloads the record to obtain the requested lock. Pass an SQL locking clause to append the end of the SELECT statement or pass true for “FOR UPDATE” (the default, an exclusive row lock). Returns the locked record.
1Note
Only works within a transaction
Of course, this has to be done in a transaction, like so:
# we've loaded user earlier and did some checks which took some time
# to make sure, updates made meanwhile by other threads don't lead to
# optimistic locking errors here, we do this when finally suspending
User.transaction do
user.lock!
user.suspended = 1
user.save!
end