mod*_*ron 138 model ruby-on-rails callback observer-pattern ruby-on-rails-4
我正在我的模型观察器中设置一个after_save回调,只有当模型的已发布属性从false更改为true 时才发送通知.既然方法改变了?只有在保存模型之前才有用,我目前(并且未成功)尝试这样做的方式如下:
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
Run Code Online (Sandbox Code Playgroud)
有没有人对处理这个问题的最佳方法有任何建议,最好使用模型观察者回调(以免污染我的控制器代码)?
Rad*_*sky 170
在你的after_update模型上的过滤器,你可以使用_changed?访问(至少在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
Run Code Online (Sandbox Code Playgroud)
它只是有效.
Jac*_*dek 165
对于那些想要了解保存后更改的人,您应该使用
model.saved_changes
Run Code Online (Sandbox Code Playgroud)
这有点像after_save但它仍然有效after_save,等等.我发现这些信息很有用,所以也许你也会这样.
在Rails 5.1+中,这是不推荐使用的.而是after_save在after_save回调中使用.
Fre*_*ang 59
对于后来看到这个的人,因为它目前(2017年8月)在谷歌上面:值得一提的是,这种行为将在Rails 5.2中被改变,并且在Rails 5.1中有弃用警告,因为ActiveModel :: Dirty改变了一点.
我该怎么改变?
如果你attribute_changed?在after_*-callbacks中使用方法,你会看到如下警告:
弃用警告:
attribute_changed?回调后内部的行为将在下一版本的Rails中发生变化.新的返回值将反映save返回后调用方法的行为(例如,与现在返回的方法相反).要保持当前行为,请saved_change_to_attribute?改用.(在/PATH_TO/app/models/user.rb:15从some_callback调用)
正如它提到的那样,你可以通过替换函数来轻松解决这个问题saved_change_to_attribute?.例如,name_changed?成为saved_change_to_name?.
同样,如果您使用the attribute_change来获取之前的值,这也会发生变化并抛出以下内容:
弃用警告:
attribute_change回调后内部的行为将在下一版本的Rails中发生变化.新的返回值将反映save返回后调用方法的行为(例如,与现在返回的方法相反).要保持当前行为,请saved_change_to_attribute改用.(来自some_callback at /PATH_TO/app/models/user.rb:20)
同样,正如它所提到的,该方法更改saved_change_to_attribute返回的名称["old", "new"].或者使用saved_changes,返回所有更改,这些更改可以作为saved_changes['attribute'].
zea*_*uss 47
如果您可以执行此操作before_save而不是after_save,您将能够使用此:
self.changed
Run Code Online (Sandbox Code Playgroud)
它返回此记录中所有已更改列的数组.
你也可以用:
self.changes
Run Code Online (Sandbox Code Playgroud)
它返回一个已更改的列的散列,以及作为数组的结果之前和之后
"选定的"答案对我不起作用.我正在使用rails 3.1和CouchRest :: Model(基于Active Model).该_changed?方法不会在对更改的属性返回true after_update钩,只能在before_update挂钩.我能够使用(new?)around_update钩子让它工作:
class SomeModel < ActiveRecord::Base
around_update :send_notification_after_change
def send_notification_after_change
should_send_it = self.published_changed? && self.published == true
yield
Notification.send(...) if should_send_it
end
end
Run Code Online (Sandbox Code Playgroud)
您可以添加一个条件,after_update例如:
class SomeModel < ActiveRecord::Base
after_update :send_notification, if: :published_changed?
...
end
Run Code Online (Sandbox Code Playgroud)
无需在send_notification方法本身中添加条件。
| 归档时间: |
|
| 查看次数: |
93107 次 |
| 最近记录: |