如何跳过ActiveRecord回调?
可能的重复:
如何避免运行 ActiveRecord 回调?
我有这样的模型
class Vote < ActiveRecord::Base
after_save :add_points_to_user
.....
end
是是否可以以某种方式强制模型在保存时跳过调用 add_points_to_user
?可能类似于 ActiveRecord#delete
与 ActiveRecord#destroy
?
Possible Duplicate:
How can I avoid running ActiveRecord callbacks?
I have model like this
class Vote < ActiveRecord::Base
after_save :add_points_to_user
.....
end
Is it possible to somehow force model to skip calling add_points_to_user
when saved? Possibly something like ActiveRecord#delete
vs ActiveRecord#destroy
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
对于 Rails 3,ActiveSupport::Callbacks 为您提供必要的控制。我只是在数据集成场景中面临着同样的挑战,通常需要的回调需要被抛在一边。您可以集体重置_回调,或使用skip_callback来明智地禁用,如下所示:
..之后您可以在禁用 :add_points_to_user 的情况下对投票实例进行操作
For Rails 3, ActiveSupport::Callbacks gives you the necessary control. I was just facing the same challenge in a data integration scenario where normally-desirable-callbacks needed to be brushed aside. You can reset_callbacks en-masse, or use skip_callback to disable judiciously, like this:
..after which you can operate on Vote instances with :add_points_to_user inhibited
以下内容适用于 Rails 2、Rails 3 和 Rails 4:
http:// guides.rubyonrails.org/v3.2.13/active_record_validations_callbacks.html#skipping-callbacks
它提供了跳过回调的方法列表,解释了为什么在不仔细考虑的情况下使用它们是危险的。根据知识共享署名-相同方式共享 3.0 许可的规定在此转载。
The following applies to rails 2, rails 3 and rails 4:
http://guides.rubyonrails.org/v3.2.13/active_record_validations_callbacks.html#skipping-callbacks
It provides a list of methods that skip callbacks, explaining why it is dangerous to use them without careful consideration. Reprinted here under the provisions of the Creative Commons Attribution-Share Alike 3.0 License.
对于 Rails 2,但不是 Rails 3,您可以使用这些:
For Rails 2, but not Rails 3 you can use these:
这将跳过您的验证:
更多信息此处
要跳过回调和验证,您可以使用 update_column v(3.1) 或 update_all
显然这只适用于 ActiveRecord 3.1
或者:
最后你还有 i Final 选项,这将跳过一切:
好吧,最后一个它不太漂亮。
This will skip your validations:
more info here
To skipping your callbacks and validations, you can use, update_column v(3.1), or update_all
Aparentlly this only works with ActiveRecord 3.1
Or:
In the end you have also i finally option and this will skip everthing:
OK the last one it's not so pretty.