Ruby before_validation触发无限循环回叫 [英] Ruby before_validation triggers infinite loop of call back
问题描述
产品模型具有一个attribute_1。如果attribute_1需要重新计算,则将调用before_validation。它导致 SystemStackError:堆栈级别太深
,因为 self.save!
触发 before_validation
。如何停止无限循环的回叫。
before_validation:method_1,:if => :recalculation_required_attribute
我正在使用 lock_version
。 update_all不会增加 lock_version
。所以我正在使用保存!
。
def method_1
####
## ##
如果self.lock_version == Product.find(self.id).lock_version
Product.where(:id => self.id).update_all(属性)
self。属性=属性
self.save!
结束
结束
您不需要 self.save!
那里:您已经在事务中了,所以只要做想做的事情,让Rails在完成后保存记录即可。 / p>
侧面注释:
-
Product.where(:id => self.id).update_all(属性)
可能可以重写为products.update_all(attributes)
(关联为this_model has_many:products
-
self.attributes =属性
是多余的,除非属性
是一个实例方法。
Product Model has an attribute_1. If recalculation is required for attribute_1 then before_validation will call. It giving SystemStackError: stack level too deep
because self.save!
triggers the before_validation
. How to stop infinite loop of call back.
before_validation :method_1, :if => :recalculation_required_attribute
I am using optimistic locking using lock_version
. 'update_all' will not increase the lock_version
. So I am using save!
. It is calling the infinite look of call back.
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
You don't need self.save!
there: you are already inside the transaction, so just do whatever you want to do and let Rails save the record once you are done.
Sidenotes:
Product.where(:id => self.id).update_all(attributes)
probably could be rewritten asproducts.update_all(attributes)
(having the associationthis_model has_many :products
self.attributes = attributes
is redundant unlessattributes
is an instance method.
这篇关于Ruby before_validation触发无限循环回叫的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!