Optimistic Locking
suggest changeOptimistic locking needs an integer lock_version column (the default name). Without it, Active Record does not check for a stale write, and the second save below succeeds.
user_one = User.find(1)
user_two = User.find(1)
user_one.name = "John"
user_one.save
# at the same time, another request still holds the original lock_version
user_two.name = "Doe"
user_two.save # raises ActiveRecord::StaleObjectError
The first save increments lock_version. The second object still has the old value, so Active Record raises instead of overwriting the row.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents