回调之后`attribute_changed?`的行为将会改变

Mar*_*tin 15 ruby-on-rails

我刚刚将一个项目升级到Rails 5.1.0,我看到了这个弃用警告.

DEPRECATION WARNING: The behavior of `attribute_changed?` 
inside of after callbacks will be changing in the next version of Rails.
The new return value will reflect the behavior of calling the method 
after `save` returned (e.g. the opposite of what it returns now). 
To maintain the current behavior, use `saved_change_to_attribute?` instead. 
Run Code Online (Sandbox Code Playgroud)

我的代码看起来像这样

class MyClass
  before_valiadtion :my_method

  def my_method
    if name_changed?
      ...
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

我不完全理解弃用警告.如果我使用saved_change_to_name它,它会在保存后检查它,但这是在验证回调之前.

我也注意到,如果我改变了name_changed?saved_change_to_name我的规格是不及格.

我很难理解适当的方法应该是什么.在我看来,在它完成工作之前是怎么回事,没有完全理解这种变化背后的原因以及我应该如何避免这些弃用警告.

Jan*_*sch 12

这些方法新的名称,可以更清楚地表达您正在寻找刚刚保存的更改,或者即将保存的更改.

在你的情况下,后者,你应该使用will_save_change_to_attribute?(:name).

弃用警告确实具有误导性,因为它只提到第一种情况,并假设它必须在后回调中发生.