产品模型有一个attribute_1。如果需要重新计算attribute_1则before_validation将调用。它SystemStackError: stack level too deep
,因为self.save!
触发before_validation
。如何停止回调的无限循环。
before_validation :method_1, :if => :recalculation_required_attribute
我正在使用lock_version
的乐观锁定。"update_all"不会增加lock_version
。所以我正在使用save!
.它正在召唤无限的回电。
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
你不需要self.save!
:你已经在事务中了,所以只要做任何你想做的事情,一旦你完成,让Rails保存记录。
旁注:
Product.where(:id => self.id).update_all(attributes)
可能可以重写为products.update_all(attributes)
(具有关联this_model has_many :products
self.attributes = attributes
是冗余的,除非attributes
是实例方法。