Browse Source

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

Rolf Schmidt 3 years ago
parent
commit
dc734791c4
3 changed files with 39 additions and 8 deletions
  1. 1 1
      app/models/data_privacy_task.rb
  2. 18 1
      app/models/organization.rb
  3. 20 6
      spec/models/organization_spec.rb

+ 1 - 1
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

+ 18 - 1
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

+ 20 - 6
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