Ruby before_validation触发无限循环回叫 [英] Ruby before_validation triggers infinite loop of call back

查看:59
本文介绍了Ruby before_validation触发无限循环回叫的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

产品模型具有一个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 as products.update_all(attributes) (having the association this_model has_many :products
  • self.attributes = attributes is redundant unless attributes is an instance method.

这篇关于Ruby before_validation触发无限循环回叫的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆