Rails 6.1 adds *_previously_was attribute methods

Abhay Nikam

By Abhay Nikam

on December 3, 2019

This blog is part of our  Rails 6.1 series.

Rails 6.1 adds *_previously_was attribute methods for dirty tracking the previous attribute value after the model is saved or reset. *_previously_was returns the previous attribute value that was changed before the model was saved

Before Rails 6.1, to retrieve the previous attribute value, we used *_previous_change or previous_changes.

Here is how it can be used.

Rails 6.0.0

1>> user = User.new
2=> #<User id: nil, name: nil, email: nil, created_at: nil, updated_at: nil>
3
4>> user.name = "Sam"
5
6# *_was returns the original value. In this example, the name was initially nil.
7>> user.name_was
8=> nil
9>> user.save!
10
11# After save, the original value is set to "Sam". To retrieve the
12# previous value, we had to use `previous_changes`.
13>> user.previous_changes[:name]
14=> [nil, "Sam"]

Rails 6.1.0

1>> user = User.find_by(name: "Sam")
2=> #<User id: 1, name: "Sam", email: nil, created_at: "2019-10-14 17:53:06", updated_at: "2019-10-14 17:53:06">
3
4>> user.name = "Nick"
5>> user.name_was
6=> "Sam"
7
8>> user.save!
9
10>> user.previous_changes[:name]
11=> ["Sam", "Nick"]
12
13# *_previously_was returns the previous value.
14>> user.name_previously_was
15=> "Sam"
16
17# After reload, all the dirty tracking
18# attributes is reset.
19>> user.reload
20>> user.name_previously_was
21=> nil

Check out the pull request for more details on this.

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.