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

>> user = User . new => #<User id: nil, name: nil, email: nil, created_at: nil, updated_at: nil> >> user . name = "Sam" # *_was returns the original value. In this example, the name was initially nil. >> user . name_was => nil >> user . save! # After save, the original value is set to "Sam". To retrieve the # previous value, we had to use `previous_changes`. >> user . previous_changes [ :name ] => [ nil , "Sam" ]

Rails 6.1.0

>> user = User . find_by ( name: "Sam" ) => #<User id: 1, name: "Sam", email: nil, created_at: "2019-10-14 17:53:06", updated_at: "2019-10-14 17:53:06"> >> user . name = "Nick" >> user . name_was => "Sam" >> user . save! >> user . previous_changes [ :name ] => [ "Sam" , "Nick" ] # *_previously_was returns the previous value. >> user . name_previously_was => "Sam" # After reload, all the dirty tracking # attributes is reset. >> user . reload >> user . name_previously_was => nil

Check out the pull request for more details on this.