2017-07-16 24 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?只應該工作好!