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
attributes["lock_version"] += 1
attributes["updated_at"] = Time.now
Product.where(:id => self.id).update_all(attributes)
self.attributes = attributes
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
and can't self.save!
because it will trigger the before_validation: method1
for infinite times.
If I do like following will optimistic locking work using update_all?
attributes["lock_version"] = 1 +1
attributes["updated_at"] = Time.now
Product.where(:id => self.id).update_all(attributes)
You can check more information on lock_version
Aucun commentaire:
Enregistrer un commentaire