Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Optimistic locking in rails

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 263
    Comment on it

    Optimistic locking is used to restrict updation of a record by multiple user at the same time . For example we have two user u1 and u2 and both of them is trying to edit the same record from a model City . While u1 is editing the record u2 comes and update the record . Now if u1 submits the form he will get ActiveRecord::StaleObjectError exception .

    @city1 = City.find(42) #accessed by u1
    @city2 = City.find(42)    #accessed by u2
    
    @city2.zip_code = 248001
    @city2.save
    
    @city1.zip_code = 700115
    @city1.save #raises ActiveRecord::StaleObjectError
    

    Activerecord does this by maintaining a column lock_version. The default value of this column should be 0 . In fact we can name the column as custom_locking_column and then go back to model to set this as locking column.

      class City < ActiveRecord::Base
      set_locking_column :custom_locking_column
    end
    

    Optimistic locking prevents the changes made by one user to be overwritten by another user unknowingly.

    Here one thing we need to take care we must have the locking column in the edit form like this

    <%= form_for @city do |form| %>
       <%= form.hidden_field :lock_version %>
       <%# ... other inputs %>
    <% end %>
    

    If we want to turn off this behaviour we can do it like this:

    ActiveRecord::Base.lock_optimistically = false

    in the application.rb file.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: