Last Updated: February 25, 2016
·
585
· amydoesntlai

Rails #changes method

Sometimes I don’t think about blogging things I’m learning because I worry that I’ve misunderstood a concept and would be posting false information, which increases in likelihood as the concept gets harder and increases in embarrassment as the concept gets easier. But my more-experienced co-worker didn’t know about the magical Rails #changes method and had written his own from scratch, so it seemed ok for me to post about this:

@object.changed? tells you if your object has changed since its last save.

@object.changes returns a hash mapping each changed attribute to an array containing its old value and its new value. Very useful for logging.

@poll = Poll.new(:name => "Foo", :topic => "Bar")
@poll.save
@poll.topic = "Baz"
@poll.changed? #=> true
@poll.changes #=> {"topic" => ["Bar", "Baz"]}
@poll.save
@poll.changed? #=> false
@poll.changes #=> {}

http://api.rubyonrails.org/classes/ActiveModel/Dirty.html