在保存记录之前进行设计,它会检查属性是否已更改,如果是,则会执行特殊操作:
def send_devise_notification(notification, *args)
# If the record is new or changed then delay the
# delivery until the after_commit callback otherwise
# send now because after_commit will not be called.
if new_record? || changed?
pending_notifications << [notification, args]
else
# Devise: send emails with background job
devise_mailer.send(notification, self, *args).deliver_later
end
end
以下一行现在让我感到沮丧:
if new_record? || changed?
DEPRECATION WARNING: The behavior of '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_changes?' instead.
当我使用saved_changes?
代替changed?
代码时,代码将无法正常工作,因为在此步骤中记录尚未保存
e.g。
user.email = "hello@example.com"
user.changed? => true
user.saved_changes? => false
我应该使用哪种方法?如何防止去反应警告?感谢
答案 0 :(得分:2)
该消息意味着{after}之后回调的changed?
内部行为会有所不同。因为记录已经保存,您可以使用saved_changes?
代替它,并且它可以很好地处理这些回调
但是如果你想在回调之前使用它,例如before_save
然后离开changed?
并且不要替换它,因为它将像以前一样正常工作
如果您不关心对象是否已保存。你可以检查它们new_record? || saved_changes? || changed?
有关更改用户电子邮件的示例。设计将在保存后发送确认,因此saved_changes?
只能运作良好!
答案 1 :(得分:0)
您应该改用saved_changes?
。