diff --git a/app/models/comment.rb b/app/models/comment.rb index e7e8d6833..eaf5e1e39 100644 --- a/app/models/comment.rb +++ b/app/models/comment.rb @@ -119,6 +119,10 @@ class Comment < ApplicationRecord processed_html.html_safe end + def root_exists? + ancestry && Comment.exists?(id: ancestry) + end + private def update_notifications @@ -148,7 +152,7 @@ class Comment < ApplicationRecord end def adjust_comment_parent_based_on_depth - self.parent_id = parent.descendant_ids.last if parent && (parent.depth > 1 && parent.has_children?) + self.parent_id = parent.descendant_ids.last if parent_exists? && (parent.depth > 1 && parent.has_children?) end def wrap_timestamps_if_video_present! @@ -218,16 +222,13 @@ class Comment < ApplicationRecord expire_root_fragment end - def root_exists? - ancestry && Comment.exists?(id: ancestry) - end - def send_email_notification Comments::SendEmailNotificationWorker.perform_async(id) end def should_send_email_notification? - parent_user.class.name != "Podcast" && + parent_exists? && + parent_user.class.name != "Podcast" && parent_user != user && parent_user.email_comment_notifications && parent_user.email && @@ -258,4 +259,8 @@ class Comment < ApplicationRecord def notify_slack_channel_about_warned_users Slack::Messengers::CommentUserWarned.call(comment: self) end + + def parent_exists? + parent_id && Comment.exists?(id: parent_id) + end end diff --git a/spec/models/comment_spec.rb b/spec/models/comment_spec.rb index f1c7fb4da..ef9ad49a9 100644 --- a/spec/models/comment_spec.rb +++ b/spec/models/comment_spec.rb @@ -385,4 +385,18 @@ RSpec.describe Comment, type: :model do end end end + + describe "#root_exists?" do + let(:root_comment) { create(:comment) } + let(:comment) { create(:comment, ancestry: root_comment.id) } + + it "returns true if root is present" do + expect(comment.root_exists?).to eq(true) + end + + it "returns false if root has been deleted" do + root_comment.destroy + expect(comment.reload.root_exists?).to eq(false) + end + end end