Today I Learned

hashrocket A Hashrocket project

Inspect Your Previous Changes

Today I found a nice ActiveModel method for inspecting previous changes, previous_changes (SQL has been removed):

[1] pry(main)> k = Kit.first
=> #<Kit:0x007fb487cec988 id: 1, name: "Foo", ... >
[2] pry(main)> k.name = 'Bar'
=> "Bar"
[3] pry(main)> k.save
=> true
[4] pry(main)> k.previous_changes
=> {"name"=>["Foo", "Bar"], "updated_at"=>[Fri, 20 Nov 2015 17:57:50 UTC +00:00, Fri, 20 Nov 2015 18:00:51 UTC +00:00]}

If nothing was updated, the method returns an empty hash.

[1] pry(main)> k = Kit.first
=> #<Kit:0x007fb487dc47e8 id: 1, name: "Foo", ... >
[2] pry(main)> k.name = 'Foo'
=> "Foo"
[3] pry(main)> k.save
=> true
[4] pry(main)> k.previous_changes
=> {}

I can imagine many practical and potentially foolish applications for this information... planning to work it into a test at some point. ActiveModel::Dirty is full of interesting methods like this.

http://apidock.com/rails/ActiveModel/Dirty/previous_changes

See More #rails TILs
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.