如何避免运行 ActiveRecord 回调? [英] How can I avoid running ActiveRecord callbacks?

查看:27
本文介绍了如何避免运行 ActiveRecord 回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些具有 after_save 回调的模型.通常这很好,但在某些情况下,例如在创建开发数据时,我想在不运行回调的情况下保存模型.有没有一种简单的方法可以做到这一点?类似于...

I have some models that have after_save callbacks. Usually that's fine, but in some situations, like when creating development data, I want to save the models without having the callbacks run. Is there a simple way to do that? Something akin to...

Person#save( :run_callbacks => false )

Person#save_without_callbacks

我查看了 Rails 文档并没有找到任何内容.然而,根据我的经验,Rails 文档并不总是能说明全部情况.

I looked in the Rails docs and didn't find anything. However in my experience the Rails docs don't always tell the whole story.

更新

我发现 一篇博文,解释了如何从这样的模型中删除回调:

I found a blog post that explains how you can remove callbacks from a model like this:

Foo.after_save.clear

我找不到记录该方法的位置,但它似乎有效.

I couldn't find where that method is documented but it seems to work.

推荐答案

此解决方案仅适用于 Rails 2.

This solution is Rails 2 only.

我刚刚调查了这个问题,我想我有一个解决方案.您可以使用两种 ActiveRecord 私有方法:

I just investigated this and I think I have a solution. There are two ActiveRecord private methods that you can use:

update_without_callbacks
create_without_callbacks

您将不得不使用 send 来调用这些方法.示例:

You're going to have to use send to call these methods. examples:

p = Person.new(:name => 'foo')
p.send(:create_without_callbacks)

p = Person.find(1)
p.send(:update_without_callbacks)

这绝对是您真正想在控制台中或在进行一些随机测试时使用的东西.希望这会有所帮助!

This is definitely something that you'll only really want to use in the console or while doing some random tests. Hope this helps!

这篇关于如何避免运行 ActiveRecord 回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆