How to get old column value in callback?

In after_update , in my model. How can I get the old column value?

+4
source share
1 answer

changed_attributes() method of your model will give you a hash of the changed attributes with their original values, even after_udpate . More information and other related methods here .

 class MyModel < ActiveRecord::Base after_update :log_changed def log_changed puts "changed attributes:" puts changed_attributes.inspect end end 

... gives the following in the console:

 $ rails console Loading development environment (Rails 3.0.7) test(dev)> m = MyModel.first => #<MyModel id: 134611365, name: "oldname", created_at: "2011-09-16 10:27:53", updated_at: "2011-09-20 11:58:11"> test(dev)> m.name = 'newname' => "newname" test(dev)> m.save SQL (0.2ms) BEGIN SQL (0.4ms) SHOW TABLES AREL (0.2ms) UPDATE `mymodels` SET `updated_at` = '2011-09-20 12:07:34', `name` = 'newname' WHERE `mymodels`.`id` = 134611365 changed attributes: {"name"=>"oldname", "updated_at"=>Tue, 20 Sep 2011 11:58:11 UTC +00:00} SQL (83.9ms) COMMIT => true test(dev)> m.changed_attributes => {} 
+7
source

All Articles