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.

Written byAbhay Nikam
Related blogs
- 01Rails 6.1 adds invert_where methodMay 4, 2021 · Chimed Palden
- 02Rails 6.1 adds in: option to validate numeric rangesApril 14, 2021 · Akanksha Jain
- 03Rails 6.1 adds delegated_type to ActiveRecordApril 6, 2021 · Akhil Gautam
- 04Rails 6.1 adds nulls_first and nulls_last to ArelMarch 9, 2021 · Berin Larson