diff --git a/app/models/dmail.rb b/app/models/dmail.rb index 54b167242..dafdc9f47 100644 --- a/app/models/dmail.rb +++ b/app/models/dmail.rb @@ -6,10 +6,11 @@ class Dmail < ApplicationRecord belongs_to :owner, :class_name => "User" belongs_to :to, :class_name => "User" belongs_to :from, :class_name => "User" - has_many :moderation_reports, as: :model + has_many :moderation_reports, as: :model, dependent: :destroy before_create :autoreport_spam after_save :update_unread_dmail_count + after_destroy :update_unread_dmail_count after_commit :send_email, on: :create deletable @@ -160,7 +161,7 @@ class Dmail < ApplicationRecord end def update_unread_dmail_count - return unless saved_change_to_id? || saved_change_to_is_read? || saved_change_to_is_deleted? + return unless saved_change_to_id? || saved_change_to_is_read? || saved_change_to_is_deleted? || destroyed? owner.with_lock do unread_count = owner.dmails.active.unread.count diff --git a/test/unit/dmail_test.rb b/test/unit/dmail_test.rb index 3c5b65415..716b02867 100644 --- a/test/unit/dmail_test.rb +++ b/test/unit/dmail_test.rb @@ -104,6 +104,31 @@ class DmailTest < ActiveSupport::TestCase end end + context "destroying a dmail" do + setup do + @recipient = create(:user) + @dmail = Dmail.create_split(from: @user, to: @recipient, creator_ip_addr: "127.0.0.1", title: "foo", body: "foo") + @modreport = create(:moderation_report, model: @dmail) + end + + should "update both users' unread dmail counts" do + assert_equal(0, @user.reload.unread_dmail_count) + assert_equal(1, @recipient.reload.unread_dmail_count) + + @user.dmails.last.destroy! + @recipient.dmails.last.destroy! + + assert_equal(0, @user.reload.unread_dmail_count) + assert_equal(0, @recipient.reload.unread_dmail_count) + end + + should "destroy any associated moderation reports" do + assert_equal(1, @dmail.moderation_reports.count) + @dmail.destroy! + assert_equal(0, @dmail.moderation_reports.count) + end + end + context "during validation" do subject { FactoryBot.build(:dmail) }