From b180a85e7fde62f54adbd142fe69ff2a353039cf Mon Sep 17 00:00:00 2001 From: Rolf Schmidt Date: Tue, 4 Jan 2022 12:44:28 +0100 Subject: [PATCH] Performance: Only update specific calendars on destroy and not loop over all. --- app/models/calendar.rb | 12 ++++-------- spec/models/calendar_spec.rb | 13 +++++++++++++ 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/app/models/calendar.rb b/app/models/calendar.rb index d9fbc20be..af804efa3 100644 --- a/app/models/calendar.rb +++ b/app/models/calendar.rb @@ -373,18 +373,14 @@ returns end # check if sla's are refer to an existing calendar - default_calendar = Calendar.find_by(default: true) - Sla.find_each do |sla| - if !sla.calendar_id - sla.calendar_id = default_calendar.id - sla.save! - next - end - if !Calendar.exists?(id: sla.calendar_id) + if destroyed? + default_calendar = Calendar.find_by(default: true) + Sla.where(calendar_id: id).find_each do |sla| sla.calendar_id = default_calendar.id sla.save! end end + true end diff --git a/spec/models/calendar_spec.rb b/spec/models/calendar_spec.rb index c3d368ed0..ba99f3ac7 100644 --- a/spec/models/calendar_spec.rb +++ b/spec/models/calendar_spec.rb @@ -43,6 +43,19 @@ RSpec.describe Calendar, type: :model do expect { described_class.first.destroy } .to change { calendar.reload.default }.to(true) end + + context 'when sla has destroyed calendar set' do + let(:sla) { create(:sla, calendar: described_class.first) } + + before do + sla + end + + it 'sets the new default calendar to the sla' do + expect { described_class.first.destroy } + .to change { sla.reload.calendar }.to(calendar) + end + end end end