gpt4 book ai didi

ruby-on-rails - 确定 Rails after_save 回调中更改了哪些属性?

转载 作者:行者123 更新时间:2023-12-03 04:26:09 26 4
gpt4 key购买 nike

我在模型观察器中设置了 after_save 回调,仅当模型的 published 属性从 false 更改为 true 时才发送通知。由于诸如 changed? 之类的方法仅在保存模型之前有用,因此我当前(但未成功)尝试执行此操作的方式如下:

def before_save(blog)
@og_published = blog.published?
end

def after_save(blog)
if @og_published == false and blog.published? == true
Notification.send(...)
end
end

有人对处理此问题的最佳方法有任何建议,最好使用模型观察者回调(以免污染我的 Controller 代码)?

最佳答案

Rails 5.1+

使用saved_change_to_published?:

class SomeModel < ActiveRecord::Base
after_update :send_notification_after_change

def send_notification_after_change
Notification.send(…) if (saved_change_to_published? && self.published == true)
end

end

或者,如果您愿意,saved_change_to_attribute?(:published)

rails 3–5.1

Warning

This approach works through Rails 5.1 (but is deprecated in 5.1 and has breaking changes in 5.2). You can read about the change in this pull request.

在模型的 after_update 过滤器中,您可以使用 _changed? 访问器。例如:

class SomeModel < ActiveRecord::Base
after_update :send_notification_after_change

def send_notification_after_change
Notification.send(...) if (self.published_changed? && self.published == true)
end

end

它确实有效。

关于ruby-on-rails - 确定 Rails after_save 回调中更改了哪些属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3861777/

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