2017-05-10 21 views
12

我剛將一個項目升級到Rails 5.1.0,我看到了這個棄用警告。回調函數後面`attribute_changed?`的行爲將會改變

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. 

我的代碼看起來像這樣

class MyClass 
    before_valiadtion :my_method 

    def my_method 
    if name_changed? 
     ... 
    end 
    end 
end 

我完全不明白棄用警告。如果我使用saved_change_to_name,它會在保存後檢查它,但這是在驗證回調之前。

我還注意到,如果我將name_changed?更改爲saved_change_to_name,我的規格未通過。

我很難理解什麼是適當的方法。在我看來,它是如何在它做好工作之前,沒有完全理解這個變化背後的原因,以及我應該如何避免這些棄用警告。

+0

你還在看這個問題嗎?我試圖用'before_validation'回調來自我復​​制,但棄用警告不顯示(Rail 5.1.1)。 – sman591

回答

7

new names for these methods更清楚地表達無論您正在尋找一個變化是剛剛保存,或一個是將被保存

在你的情況下,後一個,你應該使用will_save_change_to_attribute?(:name)

棄用警告真的很容易讓人誤解,因爲它只提到第一種情況,並假定它必須發生在回調後。

相關問題