2017-07-16 25 views
0

设计节省记录之前,它会检查,如果属性改变,如果是,则执行特殊行动:已更改? depreaction的Rails 5.1.2

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 

http://www.rubydoc.info/github/plataformatec/devise/Devise%2FModels%2FAuthenticatable%3Asend_devise_notification

下面这行现在给我一个depreaction:

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.

当I U se saved_changes?而不是changed?代码将无法正常工作,因为在此步骤中记录尚未保存

例如,

user.email = "[email protected]" 
user.changed? => true 
user.saved_changes? => false 

应该用哪种方法代替?如何防止depreaction警告?谢谢

回答

1

该消息意味着changed?将在像after_create或after_save之类的回调之后在内部表现不同。因为该记录将被保存已经可以使用saved_changes?代替,它会在这些回调

但是,如果你想使用它的回调例如before_save 之前然后离开changed?并没有取代它,因为它会工作得很好像以前一样正常工作

如果您不关心对象是否已保存。你可以只检查它们两个new_record? || saved_changes? || changed?

对于你提到的有关更改用户电子邮件的例子。设计保存后会发送确认saved_changes?只应该工作好!