Fixes #3688 - Removing organizations removes user and ticket as well.

This commit is contained in:
Rolf Schmidt 2021-08-09 09:47:42 +01:00
parent d11d1d4106
commit dc734791c4
3 changed files with 39 additions and 8 deletions

View file

@ -32,7 +32,7 @@ class DataPrivacyTask < ApplicationModel
save! save!
if delete_organization? if delete_organization?
deletable.organization.destroy deletable.organization.destroy(associations: true)
else else
deletable.destroy deletable.destroy
end end

View file

@ -24,7 +24,6 @@ class Organization < ApplicationModel
before_create :domain_cleanup before_create :domain_cleanup
before_update :domain_cleanup before_update :domain_cleanup
before_destroy :delete_associations
validates :name, presence: true validates :name, presence: true
validates :domain, presence: { message: 'required when Domain Based Assignment is enabled' }, if: :domain_assignment validates :domain, presence: { message: 'required when Domain Based Assignment is enabled' }, if: :domain_assignment
@ -35,6 +34,15 @@ class Organization < ApplicationModel
sanitized_html :note sanitized_html :note
def destroy(associations: false)
if associations
delete_associations
else
unset_associations
end
super()
end
private private
def domain_cleanup def domain_cleanup
@ -51,4 +59,13 @@ class Organization < ApplicationModel
User.where(organization_id: id).find_each(&:destroy) User.where(organization_id: id).find_each(&:destroy)
Ticket.where(organization_id: id).find_each(&:destroy) Ticket.where(organization_id: id).find_each(&:destroy)
end 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 end

View file

@ -40,14 +40,28 @@ RSpec.describe Organization, type: :model do
expect(refs_organization).to eq(refs_known) expect(refs_organization).to eq(refs_known)
end end
it 'checks user deletion' do context 'with associations' do
organization.destroy it 'checks user deletion' do
expect { user.reload }.to raise_exception(ActiveRecord::RecordNotFound) 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 end
it 'checks ticket deletion' do context 'without associations' do
organization.destroy it 'checks user deletion' do
expect { ticket.reload }.to raise_exception(ActiveRecord::RecordNotFound) 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 end
describe 'when changes for member_ids' do describe 'when changes for member_ids' do