diff --git a/app/models/data_privacy_task.rb b/app/models/data_privacy_task.rb index 2ce0e1c61..6733400d1 100644 --- a/app/models/data_privacy_task.rb +++ b/app/models/data_privacy_task.rb @@ -32,7 +32,7 @@ class DataPrivacyTask < ApplicationModel save! if delete_organization? - deletable.organization.destroy + deletable.organization.destroy(associations: true) else deletable.destroy end diff --git a/app/models/organization.rb b/app/models/organization.rb index 033171e15..85fa3ad8d 100644 --- a/app/models/organization.rb +++ b/app/models/organization.rb @@ -24,7 +24,6 @@ class Organization < ApplicationModel before_create :domain_cleanup before_update :domain_cleanup - before_destroy :delete_associations validates :name, presence: true validates :domain, presence: { message: 'required when Domain Based Assignment is enabled' }, if: :domain_assignment @@ -35,6 +34,15 @@ class Organization < ApplicationModel sanitized_html :note + def destroy(associations: false) + if associations + delete_associations + else + unset_associations + end + super() + end + private def domain_cleanup @@ -51,4 +59,13 @@ class Organization < ApplicationModel User.where(organization_id: id).find_each(&:destroy) Ticket.where(organization_id: id).find_each(&:destroy) end + + def unset_associations + User.where(organization_id: id).find_each do |user| + user.update(organization_id: nil) + end + Ticket.where(organization_id: id) do |ticket| + ticket.update(organization_id: nil) + end + end end diff --git a/spec/models/organization_spec.rb b/spec/models/organization_spec.rb index e6e0c35cf..ff06428ae 100644 --- a/spec/models/organization_spec.rb +++ b/spec/models/organization_spec.rb @@ -40,14 +40,28 @@ RSpec.describe Organization, type: :model do expect(refs_organization).to eq(refs_known) end - it 'checks user deletion' do - organization.destroy - expect { user.reload }.to raise_exception(ActiveRecord::RecordNotFound) + context 'with associations' do + it 'checks user deletion' do + organization.destroy(associations: true) + expect { user.reload }.to raise_exception(ActiveRecord::RecordNotFound) + end + + it 'checks ticket deletion' do + organization.destroy(associations: true) + expect { ticket.reload }.to raise_exception(ActiveRecord::RecordNotFound) + end end - it 'checks ticket deletion' do - organization.destroy - expect { ticket.reload }.to raise_exception(ActiveRecord::RecordNotFound) + context 'without associations' do + it 'checks user deletion' do + organization.destroy + expect(user.reload.organization_id).to be nil + end + + it 'checks ticket deletion' do + organization.destroy + expect(ticket.reload.organization_id).to be nil + end end describe 'when changes for member_ids' do