使 Rails #destroy_all 运行得更快 [英] Making Rails #destroy_all run faster

查看:29
本文介绍了使 Rails #destroy_all 运行得更快的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想运行Alarm.destroy_all,但是,每个警报都与许多AlarmEvent相关联,而每个AlarmEvent又与许多相关联AlarmEvent::Measurements,两个关联都标记为 :dependent=>destroy

I want to run Alarm.destroy_all, though, each alarm is associated to many AlarmEvents, and each AlarmEvent is associated to many AlarmEvent::Measurements,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_destroyafter_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屋!

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