BigBinary Blog
We write about Ruby on Rails, React.js, React Native, remote work, open source, engineering and design.
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.
>> 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"]
>> 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.