ruby-on-railsrubypessimistic-locking

How does pessimistic locking work across requests in Rails?


If a user is editing a resource with pessimistic lock no one else can edit the resource until the editing user saves his changes. Now to my question, what happens when the editing user did not save his changes but clicks on the browser back button to get to the last view? Is the resource still locked or is the lock dismissed? The same question applies to the scenario where the editing user is on the editing view and then navigates to another view over the links in a navigation bar. Does the user needs to come back to the edit view of the specific resource and save the changes before the lock is dismissed? And if yes, how can the lock be dismissed when the edit view is exited through other buttons than the save button?


Solution

  • The usual implementation of pessimistic locks in Rails, i.e. the use of ActiveRecord::Locking::Pessimistic obtains a lock on data during a database transaction. Thus, the lock is obtained and released during a single web request and does not spawn over multiple requests (such as a wizard or a multi-step process in your app). This can be useful to ensure that concurrent requests updating the same resources do not produce inconsistent data.

    If you need a lock to be held over multiple requests, you need to implement this in some other way which is not dependent on an open database transaction.

    To answer your question specifically: the pessimistic lock is not held while the user edits data in their browser. It is obtained when the user sends their changes to the server and released after. Thus, locking is unaffected if the user clicks the back button or doesn't send any changes because the lock is not held at that point.