cwninja的答案應該做的伎倆,但有一點點它。
首先,基本屬性處理是通過write_attribute方法完成的,因此您應該點擊此處。
Rails也有一個內置的回調結構,雖然它不允許傳遞帶有點煩惱的參數,但可以很好地利用它。
使用自定義的回調,你可以做這樣的:
class Person < ActiveRecord::Base
def write_attribute(attr_name, value)
attribute_changed(attr_name, read_attribute(attr_name), value)
super
end
private
def attribute_changed(attr, old_val, new_val)
logger.info "Attribute Changed: #{attr} from #{old_val} to #{new_val}"
end
end
如果您想嘗試使用Rails的回調(尤其是有用的,如果你可能有多個回調和/或子類),你可以做這樣的事情:
class Person < ActiveRecord::Base
define_callbacks :attribute_changed
attribute_changed :notify_of_attribute_change
def write_attribute(attr_name, value)
returning(super) do
@last_changed_attr = attr_name
run_callbacks(:attribute_changed)
end
end
private
def notify_of_attribute_change
attr = @last_changed_attr
old_val, new_val = send("#{attr}_change")
logger.info "Attribute Changed: #{attr} from #{old_val} to #{new_val}"
end
end
彼得,這是美麗的,將爲我節省一大筆「write_attribute」,我遍佈我的代碼。謝謝! – BushyMark 2009-10-04 00:32:34
似乎這隻適用於Rails 2。 – lulalala 2013-10-23 10:41:19
通過谷歌來到這個沒有檢查日期。這個更近期的演練做了我所需要的:[如何跟蹤'after_callbacks'中模型的變化](http://ruby-journal.com/how-to-track-changes-with-after-callbacks-in- rails-3-or-newer /) – Jay 2014-07-03 19:10:03