What is the ActiveModel method attribute "_was" used for?
Asked Answered
E

1

18

When using autocomplete in the console, I often see "_was" postpended to my attributes. But I can't find any documentation or best practices for usage. What does it do and how should it be used?

Example: user.fname has the method user.fname_was

Using source_location, I've tracked it down to: active_model/attribute_methods.rb", line 296 but there isn't anything specific.

Eighty answered 16/12, 2012 at 23:43 Comment(0)
T
49

That is a part of ActiveModel::Dirty You can see it here https://github.com/rails/rails/blob/af64ac4e5ce8406137d5520fa88e8f652ab703e9/activemodel/lib/active_model/dirty.rb#L146 Example

person = Person.find_by_name('Uncle Bob')
person.changed?       # => false

Change the name:

person.name = 'Bob'
person.changed?       # => true
person.name_changed?  # => true

#method _was return prev attribute value
person.name_was  # => 'Uncle Bob'  
person.name_change    # => ['Uncle Bob', 'Bob']
person.name = 'Bill'
person.name_change    # => ['Uncle Bob', 'Bill']
Timbale answered 16/12, 2012 at 23:50 Comment(2)
just was playing with it few months ago, I was digging in source codeTimbale
I would also note that calling person.save! will reset name_was to be the same as the new nameLeer

© 2022 - 2024 — McMap. All rights reserved.