All posts by rtyler

Ruby on Rails Cha Cha Cha Changes

Handy methods available on a Rails model to check if there has been changes to any/all fields, also find out what the changes were; fire up console and look up any object:

>> User.first
=> #<User id: 1, login: “billy.bob”, name: “Billy Bob”, email: nil>

Set a variable to the last result using underscore, useful little shortcut:

>> usr =  _
=> #<User id: 1, login: “billy.bob”, name: “Billy Bob”, email: nil>

Set one of your model attributes to a new value:

>> = ‘Ryan  Tyler’
=> “Ryan  Tyler”

.changes on your variable will show a hash of the changes made, but not yet saved:

>> usr.changes
=> {“name”=>[“Billy Bob”, “Ryan Tyler”]}

You can inspect any part of the array

>> usr.changes[“name”]
=> [“Billy Bob”, “Ryan Tyler”]

>> usr.changes[“name”][0]
=> “Billy Bob”

>> usr.changes[“name”][1]
=> “Ryan Tyler”

If you are interested when any attribute has changed then changed? will return a Boolean

>> usr.changed?
=> true

Test an individual attribute, in a model on some callback you may use self.name_changed?

>> usr.name_changed?
=> true

>> usr.email_changed?
=> false