How to get old value of column in a callback?
On after_update
, in my model. How can I g开发者_Go百科et the old value of a column?
changed_attributes()
method of your model will get you a hash of changed attributes with their original values, even after_udpate
. More info and more 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
=> {}
精彩评论