LoginSignup
91
68

More than 5 years have passed since last update.

ActiveRecordのchanged?が非推奨になっている

Last updated at Posted at 2017-06-13

発生した問題

Rails5.1を使ってみようと思い、いつものようにコードを書いていると、大量のwarningが出てることに気づいた。

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. (called from メソッド at /path/to/mode.rb:xx)

調べてみると、どうやら書き方が変わるらしい。
https://github.com/rails/rails/blob/master/activerecord%2Flib%2Factive_record%2Fattribute_methods%2Fdirty.rb#L22-L29

save前とsave後で扱うメソッドが変わるようなので、注意が必要。

解決方法

save前

  • {カラム名}_changed? の代わりに will_save_change_to_{カラム名}?
  • {カラム名}_was の代わりに {カラム名}_in_database

save後

  • {カラム名}_changed? の代わりに saved_change_to_{カラム名}?
  • {カラム名}_was の代わりに {カラム名} _before_last_save
91
68
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
91
68