确定什么属性改变了Rails的after_save回调? [英] Determine what attributes were changed in Rails after_save callback?
问题描述
我在模型观察器中设置一个after_save回调,只有当模型的已发布属性从false更改为true时,才会发送通知。由于诸如改变之类的方法仅在保存模型之前有用,因此我目前(并未成功)尝试这样做的方式如下:
def before_save(blog)
@og_published = blog.published?
end
def after_save(blog)
如果@og_published == false和blog.published? == true
Notification.send(...)
end
end
$ b b
有没有人有任何建议,最好的方式来处理这个,最好使用模型观察者回调(以免污染我的控制器代码)?
在您的 after_update
过滤器中,可以使用 _changed? c $ c>存取器(至少在Rails 3,不确定Rails 2)。例如:
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
>
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)?
In your after_update
filter on the model you can use _changed?
accessor (at least in Rails 3, not sure for Rails 2). 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
It just works.
这篇关于确定什么属性改变了Rails的after_save回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!