确定在 Rails after_save 回调中更改了哪些属性? [英] Determine what attributes were changed in Rails after_save callback?
问题描述
我正在我的模型观察器中设置 after_save 回调,以便仅在模型的 published 属性从 false 更改为 true 时发送通知.由于诸如 changed? 之类的方法仅在保存模型之前有用,因此我目前(但未成功)尝试这样做的方式如下:
I'm setting up an after_save callback in my model observer to send a notification only if the model's published attribute was changed from false to true. Since methods such as changed? are only useful before the model is saved, the way I'm currently (and unsuccessfully) trying to do so is as follows:
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
是否有人对处理此问题的最佳方法有任何建议,最好使用模型观察者回调(以免污染我的控制器代码)?
Does anyone have any suggestions as to the best way to handle this, preferably using model observer callbacks (so as not to pollute my controller code)?
推荐答案
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 5.1(但在 5.1 中已弃用,并在 5.2 中进行了重大更改).您可以在此拉取请求中了解更改.
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?
访问器.例如:
In your after_update
filter on the model you can use _changed?
accessor. So for example:
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
它只是有效.
这篇关于确定在 Rails after_save 回调中更改了哪些属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!