diff --git a/app/models/conversation.rb b/app/models/conversation.rb index 97115dde6..779c7668e 100644 --- a/app/models/conversation.rb +++ b/app/models/conversation.rb @@ -61,6 +61,7 @@ class Conversation < ApplicationRecord has_many :messages, dependent: :destroy, autosave: true has_one :csat_survey_response, dependent: :destroy + has_many :notifications, as: :primary_actor, dependent: :destroy before_create :set_bot_conversation diff --git a/db/migrate/20210708140842_remove_notifications_without_primary_actor.rb b/db/migrate/20210708140842_remove_notifications_without_primary_actor.rb new file mode 100644 index 000000000..3d2583400 --- /dev/null +++ b/db/migrate/20210708140842_remove_notifications_without_primary_actor.rb @@ -0,0 +1,9 @@ +class RemoveNotificationsWithoutPrimaryActor < ActiveRecord::Migration[6.0] + def change + deleted_ids = [] + Notification.where(primary_actor_type: 'Conversation').pluck(:primary_actor_id).uniq.each_slice(1000) do |id_list| + deleted_ids << id_list - Conversation.where(id: id_list).pluck(:id) + end + Notification.where(primary_actor_type: 'Conversation', primary_actor_id: deleted_ids).destroy_all + end +end diff --git a/db/schema.rb b/db/schema.rb index cc0ad871d..694639ff1 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 2021_06_23_155413) do +ActiveRecord::Schema.define(version: 2021_07_08_140842) do # These are extensions that must be enabled in order to support this database enable_extension "pg_stat_statements" diff --git a/spec/models/conversation_spec.rb b/spec/models/conversation_spec.rb index bcfc91a70..cbbd97855 100644 --- a/spec/models/conversation_spec.rb +++ b/spec/models/conversation_spec.rb @@ -399,4 +399,15 @@ RSpec.describe Conversation, type: :model do end end end + + describe '#delete conversation' do + let!(:conversation) { create(:conversation) } + + let!(:notification) { create(:notification, notification_type: 'conversation_creation', primary_actor: conversation) } + + it 'delete associated notifications if conversation is deleted' do + conversation.destroy + expect { notification.reload }.to raise_error ActiveRecord::RecordNotFound + end + end end