mercredi 3 octobre 2018

Ruby: How to handle optimistic locking using update_all(attributes)

I am trying to implement the Optimistic Locking for Race Condition. For that, I added an extra column lock_version in the Product: Model through migration.

#Product: Model's new field:
    #  attribute_1
    #  lock_version                       :integer(4)      default(0), not null
before_validation :method_1, :if => :recalculation_required_attribute

def method_1
    ####
    ####
    if self.lock_version == Product.find(self.id).lock_version
       Product.where(:id => self.id).update_all(attributes)
       self.attributes = attributes
       self.save!
    end
end

Product Model has an attribute_1. If recalculation is required for attribute_1 then before_validation: method_1 will call.

I am using optimistic locking using lock_version. However, update_all will not increase the lock_version. So I start usingsave!. Now I am getting a new error: SystemStackError: stack level too deep because self.save! triggers the before_validation: method1. How to stop infinite loop of call back and handle optimistic locking in the above case.

Aucun commentaire:

Enregistrer un commentaire