diff --git a/app/assets/javascripts/app/models/organization.coffee b/app/assets/javascripts/app/models/organization.coffee index b01941f29..04b00abc6 100644 --- a/app/assets/javascripts/app/models/organization.coffee +++ b/app/assets/javascripts/app/models/organization.coffee @@ -1,5 +1,5 @@ class App.Organization extends App.Model - @configure 'Organization', 'name', 'shared', 'note', 'member_ids', 'active', 'updated_at' + @configure 'Organization', 'name', 'shared', 'note', 'active', 'updated_at' @extend Spine.Model.Ajax @url: @apiPath + '/organizations' @configure_attributes = [ diff --git a/app/models/organization.rb b/app/models/organization.rb index dc9ce5f24..2b83c7efa 100644 --- a/app/models/organization.rb +++ b/app/models/organization.rb @@ -15,11 +15,12 @@ class Organization < ApplicationModel include Organization::Search include Organization::SearchIndex - has_many :members, class_name: 'User', dependent: :destroy - has_many :tickets, class_name: 'Ticket', dependent: :destroy + has_many :members, class_name: 'User' + has_many :tickets, class_name: 'Ticket' 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 @@ -42,4 +43,8 @@ class Organization < ApplicationModel true end + def delete_associations + User.where(organization_id: id).find_each(&:destroy) + Ticket.where(organization_id: id).find_each(&:destroy) + end end diff --git a/spec/models/organization_spec.rb b/spec/models/organization_spec.rb index 6fe43a093..4371fbab3 100644 --- a/spec/models/organization_spec.rb +++ b/spec/models/organization_spec.rb @@ -47,6 +47,18 @@ RSpec.describe Organization, type: :model do organization.destroy expect { ticket.reload }.to raise_exception(ActiveRecord::RecordNotFound) end + + describe 'when changes for member_ids' do + let(:agent1) { create(:agent) } + let(:agent2) { create(:agent) } + let(:agent3) { create(:agent) } + let(:organization_agents) { create(:organization, member_ids: [agent1.id, agent2.id, agent3.id]) } + + it 'does not delete users' do + organization_agents.update(member_ids: [agent1.id, agent2.id]) + expect { agent3.reload }.not_to raise_error + end + end end end