Lock it carefully!

While implementing features of an app that is expected to be accessed by multiple users, we make sure to keep data consistent and not getting into a race condition, we use the locking technique.

There are two types of locking, optimistic and pessimistic locking. Here, we would be talking about pessimistic locking. To help us Rails provides us with a helpful locking module that provides support for row-level locking using SELECT … FOR UPDATE and other lock types.

So, to avoid getting into said issues above, we use locking all over our application where needed. But there was one place where locking produced an error while running specs that were caught by our CI tool although the specs were passing locally.

Turns out the locked object somehow became dirty (modified) and locking a dirty object raised an error.

Locking a record with unpersisted changes is not supported. Use `save` to persist the changes, or `reload` to discard them explicitly.

Make sure to reload or save any modified changes to your object before locking it.

user.reload.with_lock do
# ... your code here
end

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store