DEV Community

Alexander Budchanov for JetRockets

Posted on • Originally published at jetrockets.pro

Rails 5.2 changes in callbacks

In version 5.1 you may see deprecation warnings in after_save callbacks (related to changes in ActiveRecord::Dirty module).
But since 5.2 these changes were applied.

For examples, I will use Rails 4.2.11 and Rails 5.2.3 and model User with email attribute. Let's do:

u = User.new(email: 'old@domain.com')
u.save
u.email = 'new@domain.com'
u.save
Enter fullscreen mode Exit fullscreen mode

and look at after_save callback in time of last save.

1. attribute_changed?

Rails 4

> email_changed?
=> true
Enter fullscreen mode Exit fullscreen mode

Rails 5.2

> email_changed?
=> false
Enter fullscreen mode Exit fullscreen mode

but you can use saved_changes?

> saved_change_to_email?
=> true
Enter fullscreen mode Exit fullscreen mode

2. changed?

Rails 4

> changed?
=> true
Enter fullscreen mode Exit fullscreen mode

Rails 5.2

> changed?
=> false
Enter fullscreen mode Exit fullscreen mode

but you can use saved_changes?

> saved_changes?
=> true
Enter fullscreen mode Exit fullscreen mode

3. changes

Rails 4

> changes
=> {"email"=>["old@domain.com", "new@domain.com"]}
Enter fullscreen mode Exit fullscreen mode

Rails 5.2

> changes
=> {}
Enter fullscreen mode Exit fullscreen mode

but you can use saved_changes

> saved_changes
=> {"email"=>["old@domain.com", "new@domain.com"]}
Enter fullscreen mode Exit fullscreen mode

4. previous_changes

Rails 4

> previous_changes
=> {"email"=>[nil, "old@domain.com"]}
Enter fullscreen mode Exit fullscreen mode

Rails 5.2
Now, this method returns the changes that were just saved (like saved_changes).

> previous_changes
=> {"email"=>["old@domain.com", "new@domain.com"]}
Enter fullscreen mode Exit fullscreen mode

this method has no replacement.

Top comments (0)