产品型号可以由多个用户更新。但是,一次只有一个用户应该能够更新。为此,我想使用updated_at对产品模型使用乐观锁定。
我为乐观锁实现了以下代码。还有其他实现乐观锁定的方法,例如使用lock_version
。但是,由于现有代码限制,我无法使用lock_version
来实现。
Product Model
MAX_RETRIES = 3
attr_writer :original_updated_at
def original_updated_at
@original_updated_at || updated_at
end
def stale_object?
if self.updated_at > original_updated_at
@original_updated_at = nil
return true
else
return false
end
end
def public_method
##code
result = nil
begin
result = private_method
self.original_updated_at = self.updated_at
rescue ActiveRecord::StaleObjectError => e
errors.add(:base, ": Following records are changed while you were editing.")
changes.except("updated_at").each do |name, values|
errors.add(name, values)
end
rescue Exception => error
##code
end
result
end
def private_method
tries = 0
begin
raise ActiveRecord::StaleObjectError.new(self, "Product is changed while you were editing") if stale_object?
attributes = #create hash using some code
#some code
attributes["updated_at"] = Time.now.utc
Product.where(:id => self.id).update_all(attributes)
self.original_updated_at = self.updated_at
rescue ActiveRecord::StaleObjectError => e
if tries < MAX_RETRIES
tries += 1
sleep(1 + tries)
self.reload
retry
else
raise ActiveRecord::StaleObjectError.new(self, "Product is changed while you were editing")
end
end
attributes
end