【问题标题】:Rails detect if Attribute Changed Before Update - SystemStackError: stack level too deepRails 检测更新前是否更改了属性 - SystemStackError:堆栈级别太深
【发布时间】:2013-04-01 07:43:07
【问题描述】:

我想在模型更新之前检测属性是否发生了变化。

我有以下(基于:http://api.rubyonrails.org/classes/ActiveModel/Dirty.html):

before_update :changed_attributes

def changed_attributes
    self.path_changed? ? puts('Path was changed') : puts('Path was not changed')
end

但现在当我尝试编辑 Model.path 属性时,出现以下错误:

SystemStackError: stack level too deep

我听说这意味着正在发生无限递归。

在不创建 SystemStackError 的情况下执行此操作的正确方法是什么?

【问题讨论】:

    标签: ruby-on-rails model attributes callback


    【解决方案1】:

    问题是 ActiveRecord 已经有一个名为changed_attributes 的方法。很可能path_changed? 调用changed_attributes,但您重新定义了changed_attributes,它包含path_changed?。这会导致无休止的递归,并最终导致堆栈级别过深。

    尝试将您的方法名称更改为check_changed_attributes 或其他名称:

    before_update :check_changed_attributes
    
    def check_changed_attributes
      self.path_changed? ? puts 'Path was changed' : puts 'Path was not changed'
    end
    

    【讨论】:

      猜你喜欢
      • 2017-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-10
      • 2013-10-05
      • 2014-10-25
      • 1970-01-01
      • 2017-05-21
      相关资源
      最近更新 更多