本文介绍了如何避免运行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.

更新

我发现a博客文章,解释了如何从一个模型这样的删除回调:

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

你将不得不使用发送来调用这些方法。例子:

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的回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 06:41