如何在不运行Rails的回调的情况下保存模型 [英] How to save a model without running callbacks in Rails
问题描述
在Rails中保存模型时,我需要计算值。因此,我调用 calculate_averages
作为 Survey
类的回调:
I need to calculate values when saving a model in Rails. So I call calculate_averages
as a callback for a Survey
class:
before_save :calculate_averages
但是,偶尔(最初我有10k条记录需要执行此操作)我需要手动更新每条记录的所有平均值。没问题,我的代码如下:
However, occasionally (and initially I have 10k records that need this operation) I need to manually update all the averages for every record. No problem, I have code like the following:
Survey.all.each do |survey|
survey.some_average = (survey.some_value + survey.some_other_value) / 2.to_f
#and some more averages...
survey.save!
end
在运行此代码之前,我担心 calculate_averages
将被调用并重复此操作,甚至可能在我做事的方式上引起一些问题。好的,那么我想,好吧,我什么也不做,让 calculate_averages
被调用并执行其操作。问题首先是,即使您未更改记录,有没有一种方法可以强制调用回调?
Before even running this code, I'm worried the calculate_averages
is going to get called and duplicate this and probably even cause some problems with the way I'm doing things. Ok, so then I think, well I'll just do nothing and let calculate_averages
get called and do its thing. Problem there is, first, is there a way to force callbacks to get called even if you made no changes to the record?
第二,平均值的计算方式是 far 效率更高,可以根本不让回调完全被调用,并且一次对所有内容进行平均。
Secondly, the way averages are calculated it's far more efficient to simply not let the callbacks get called at all and do the averages for everything all at once. Is this possible to not let callbacks get called?
推荐答案
我相信您的要求可以通过 ActiveSupport :: Callbacks
。看看 set_callback
和 skip_callback
。
I believe what you are asking for can be achieved with ActiveSupport::Callbacks
. Have a look at set_callback
and skip_callback
.
为了即使未更改记录也强制回调被调用,您需要将回调注册到某个事件,例如保存,验证等。
。
In order to "force callbacks to get called even if you made no changes to the record", you need to register the callback to some event e.g. save, validate etc.
.
set_callback :save, :before, :my_before_save_callback
要跳过 before_save
回调,您可以这样做:
To skip the before_save
callback, you would do:
Survey.skip_callback(:save, :before, :calculate_average).
请参考链接的 ActiveSupport :: Callbacks
其他受支持的选项,例如条件和 set_callback $的块
和 skip_callback
。
这篇关于如何在不运行Rails的回调的情况下保存模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!