Active Record Attribute Methods

10 Jul 2018
add_column

You know these two getter and setter methods that are created when you add a column to a table in active record. Take name for example.

person.name # nil
person.name = 'stuart'

But here is a list of lesser known methods that are automatically created for attributes that you might find useful.

person.name?         # Boolean: calls .present? on the attribute (aka. nil, false, 0, or '')
person.name_was      # when updating a record it will return the previously set value
person.name_changed? # Boolean: if the value has changed
person.name_change   # Array: index 0 is the old value, index 1 is the new value
person.restore_name! # set the value back to what it initially set to

Want to see a list of all available methods created for each attribute? Run this with your model name and an attribute to find out!

# rails c
Person.new.methods.select {|e| e =~ /name/}
Improvements, bugs, typos? Contribute on GitHub ❤️