gpt4 book ai didi

ruby-on-rails - 回调更改的ActiveRecord属性?

转载 作者:行者123 更新时间:2023-12-03 13:41:33 24 4
gpt4 key购买 nike

我知道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

关于ruby-on-rails - 回调更改的ActiveRecord属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1513991/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com