【发布时间】:2018-10-03 10:18:15
【问题描述】:
我正在尝试实现竞争条件的乐观锁定。为此,我在 Product: Model through migration 中添加了一个额外的列 lock_version。
#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
产品型号有一个attribute_1。如果attribute_1 需要重新计算,则before_validation: method_1 将调用。
我正在使用 lock_version 进行乐观锁定。但是,update_all 不会增加lock_version。所以我开始使用save!。现在我收到一个新错误:SystemStackError: stack level too deep,因为self.save! 触发了before_validation: method1。在上述情况下如何停止无限循环的回调并处理乐观锁定。
【问题讨论】:
-
那么您要更新哪个对象的
lock_version?self或所有Product.where(:id => self.id)。你的代码太复杂了......你为什么在Product模型中做Product.find(self.id)?id不是唯一的主键吗?
标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 race-condition