我知道ActiveRecord :: Dirty及其相关方法,但是我没有看到可以用来订阅属性更改事件的方法。就像是:
class Person < ActiveRecord::Base
def attribute_changed(attribute_name, old_value, new_value)
end
#or
attribute_changed do |attribute_name, old_value, new_value|
end
end
是否有Rails标准或插件?我觉得它一定在某个地方,而我只是想念它。
最佳答案
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