Note that there are some explanatory texts on larger screens.

plurals
  1. POrails - implementing a simple lock to prevent user's from editing the same data concurrently
    text
    copied!<p>I have an app where I need to prevent users from editing data while it is being edited by a different user. I'm trying to think of the best way to do it and wanted to ask for ideas. So far, I've created a settings model that stores application wide configuration on the db in key/value pairs. So, for the lock, I have a settings instance that's called LOCKED_TABLE_UID, and it stored the user_id of the user editing the table or null (nil) if the table is free.</p> <pre><code>&gt;&gt; lock = Setting.find_by_key('LOCKED_TABLE_UID') </code></pre> <p>Then, I implemented 2 methods in my application controller to acquire and release the lock:</p> <pre><code># current_user returns the user currently logged in def acquire_lock lock = Setting.find_by_key("LOCKED_TABLE_UID") if lock.value # if lock taken, see if it's the current_user or someone else if lock.value.to_i == current_user.id.to_i return true else return false end else # lock is free, assign it to this user lock.value = current_user.id return true if lock.save end end def release_lock lock = Setting.find_by_key("LOCKED_TABLE_UID") if lock.value # the lock belongs to current_user, so he can release it if lock.value.to_i == current_user.id.to_i lock.value = nil return true if lock.save else # not your lock, go away return false end else # lock is free, quit bugging return true end end </code></pre> <p>What I want is to create some kind of block code that contains the locking mechanism, something like this:</p> <pre><code>def some_crud_action requires_locking do |lock| if lock # do some CRUD stuff here else # decline CRUD and give some error end end end </code></pre> <p>I'd appreciate help on this - but I'm also open to other suggestions on how to accomplish all that, or some things I may have overlooked. This lock doesn't have to be atomic, but fairly basic and most important - that it works :) thanks.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload