使 Rails #destroy_all 运行得更快 [英] Making Rails #destroy_all run faster
问题描述
我想运行Alarm.destroy_all
,但是,每个警报都与许多AlarmEvent
相关联,而每个AlarmEvent
又与许多相关联AlarmEvent::Measurement
s,两个关联都标记为 :dependent=>destroy
I want to run Alarm.destroy_all
, though, each alarm is associated to many AlarmEvent
s, and each AlarmEvent
is associated to many AlarmEvent::Measurement
s,being both associations marked as :dependent=>destroy
所以,当我调用 Alarm.destroy all 时,这个调用需要很长时间才能运行.有什么办法可以让它更快吗?怎么样?
So, when I invoke Alarm.destroy all, this invokation is taking ages to run. Is there any way I could make it faster? How?
到目前为止,我已经尝试过 Alarm.joins(:alarm_events).destroy_all
并且它仍然很慢.
Until now I've tried Alarm.joins(:alarm_events).destroy_all
and it is still slow.
推荐答案
destroy_all
更快的替代方案是 delete_all
但这不会追赶和破坏任何依赖项,也不会触发任何 before_destroy
或 after_destroy
钩子.
The faster alternative to destroy_all
is delete_all
but this won't chase down and destroy any dependencies, nor will it trigger any before_destroy
or after_destroy
hooks.
如果您真的很关心速度,您可能会考虑到这一点而重新编写此内容.你甚至可以把它当作一系列条件:
If you're really concerned about speed, you'd probably re-write this with this in mind. You can even rack it up as a series of conditions:
Alarm.delete_all(:id => alarm_ids)
AlarmEvent.delete_all(:alarm_id => alarm_ids)
这篇关于使 Rails #destroy_all 运行得更快的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!