Ruby before_validation触发无限循环的回调
产品型号具有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
是实例方法。