开发者

Making Rails #destroy_all run faster

开发者 https://www.devze.com 2023-03-25 20:21 出处:网络
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=&

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

So, when I invoke Alarm.destroy all, this invokation is taking ages to run. Is there any way I could make it faster? How?

Until now I've tried Alarm.joins(:alarm_events).destroy_all and it is stil开发者_StackOverflow中文版l slow.


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)


I have improved it by replacing the invokation with:

Alarm.transaction{
  AlarmEvent::Measurement.destroy_all
  AlarmEvent.destroy_all
  Alarm.destroy_all
}

This still garantees that the destroy-associated proceedures are ran, but it pre-executes a big part of them, thus avoiding a lot of "nested queries".

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号