From 7385fea270147a0b324670d58e2282054f56f0cd Mon Sep 17 00:00:00 2001 From: Jared Cosulich Date: Thu, 9 Mar 2017 11:56:39 -0500 Subject: [PATCH] syncing recipient deletion --- app/models/recipient.rb | 12 ++++++++++++ spec/models/recipient_spec.rb | 31 ++++++++++++++++++++++++++++++- 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/app/models/recipient.rb b/app/models/recipient.rb index be654c6a..eb00de07 100644 --- a/app/models/recipient.rb +++ b/app/models/recipient.rb @@ -8,6 +8,8 @@ class Recipient < ApplicationRecord validates :name, presence: true + before_destroy :sync_lists + def self.import(school, file) CSV.foreach(file.path, headers: true) do |row| school.recipients.create!(row.to_hash) @@ -22,4 +24,14 @@ class Recipient < ApplicationRecord end end + private + + def sync_lists + school.recipient_lists.each do |recipient_list| + next if recipient_list.recipient_id_array.index(id).nil? + updated_ids = recipient_list.recipient_id_array - [id] + recipient_list.update_attributes(recipient_id_array: updated_ids) + end + end + end diff --git a/spec/models/recipient_spec.rb b/spec/models/recipient_spec.rb index 43a9c7d2..bc0c1671 100644 --- a/spec/models/recipient_spec.rb +++ b/spec/models/recipient_spec.rb @@ -16,6 +16,35 @@ describe Recipient do end describe "When Deleted" do - it 'should delete all recipient_schedules' + let!(:school) { School.create!(name: 'School') } + + let!(:recipients) { create_recipients(school, 3) } + let!(:recipient_list) do + school.recipient_lists.create!(name: 'Parents', recipient_ids: recipients.map(&:id).join(',')) + end + + let!(:questions) { create_questions(3) } + let!(:question_list) do + QuestionList.create!(name: 'Parent Questions', question_ids: questions.map(&:id).join(',')) + end + + let!(:schedule) do + Schedule.create!( + name: 'Parent Schedule', + recipient_list_id: recipient_list.id, + question_list: question_list, + random: false, + frequency_hours: 24 * 7 + ) + end + + it 'should delete all recipient_schedules and update all recipient_lists' do + expect do + recipients[1].destroy + end.to change { schedule.recipient_schedules.count }.from(3).to(2) + + expect(recipient_list.recipient_ids).to eq("#{recipients[0].id},#{recipients[2].id}") + + end end end