#59 Optimistic Locking (revised)
Aug 04, 2012 | 8 minutes | Active Record
There is a chance one user will unintentionally override someone else's changes if they update a record near the same time. One solution is to use optimistic locking. The updated_at column can also be used for this as shown.



Nice idea. It should be in rails like built-in validation. Thank's Ryan.
Sidequestion: Is it better to load modules into my models? I currently use abstract models for most things (which, however, loads modules itself). But I runned into problems as the
self.abstract_class = truegotcha seems to be not widely known...The video is not working :(
Thanks so much as always! There is an episode for nearly every thing I want to do! Amazing!
Using the second method, I had a behavior with a remote form that I wanted to pass by the group. I got the first validation error just fine. If I hit submit again, however, the old value would pass the validation the second time and overwrite the value that was protected the first time around.
In other words, the conflict was not detected because @original_updated_at was set to nil and the object reloaded the new timestamp and passed the update right through. If I comment out the @original_updated_at = nil line, I get the behavior I want -- a durable block on any updates to that record.
Does this make sense? What was the value of setting @original_updated_at to nil in the code? Thanks for any advice you might have! Charles
One more quick discovery/question. With the second method, I was getting spurious locking errors added to base on creation. It turned out acts_as_list and other such plugins intercept the create process and perform some quick saves to get things in the right place. Not sure I completely understand, but I needed to pass the validation if nothing was in the changes array:
This got my simple creation action up and running again. Thanks for this great episode and any insights on whether this is a short sighted fix. Charles
One thing not mentioned in the episode is that HTTP reserves the 409 status code to indicate conflicts.
render status: :conflictalso works. Set it for your response, especially in APIs.First sign in through GitHub to post a comment.