Skip to content

Commit

Permalink
Merge pull request #2481 from Ana06/comments
Browse files Browse the repository at this point in the history
[api] Delete nobody comments without children
  • Loading branch information
David Kang committed Jan 3, 2017
2 parents 8dbb635 + 6a4d927 commit b5b5a82
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/api/app/models/comment.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ class Comment < ApplicationRecord
validates :body, :commentable, :user, presence: true

after_create :create_notification
after_destroy :delete_parent_if_unused

has_many :children, dependent: :destroy, class_name: 'Comment', foreign_key: 'parent_id'

Expand Down Expand Up @@ -81,4 +82,10 @@ def blank_or_destroy
def destroy
super
end

private

def delete_parent_if_unused
parent.destroy if parent && parent.user == User.find_nobody! && parent.children.length.zero?
end
end
26 changes: 26 additions & 0 deletions src/api/spec/models/comment_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
RSpec.describe Comment do
let(:comment_package) { create(:comment_package) }
let(:comment_package_with_parent) { create(:comment_package, parent: comment_package) }
let(:comment_package_with_parent_2) { create(:comment_package, parent: comment_package) }
let(:comment_package_with_grandparent) { create(:comment_package, parent: comment_package_with_parent) }

describe "has a valid Factory" do
it { expect(comment_package).to be_valid }
Expand Down Expand Up @@ -66,6 +68,30 @@
end
end

context "with nobody parent and a brother" do
before do
comment_package_with_parent
comment_package_with_parent_2
comment_package.blank_or_destroy
end

it 'should be destroyed' do
expect { comment_package_with_parent.blank_or_destroy }.to change { Comment.count }.by(-1)
end
end

context "with nobody parent, nobody grandparent and no brother" do
before do
comment_package_with_grandparent
comment_package_with_parent.blank_or_destroy
comment_package.blank_or_destroy
end

it 'should be destroyed' do
expect { comment_package_with_grandparent.blank_or_destroy }.to change { Comment.count }.by(-3)
end
end

context "with children" do
before do
comment_package_with_parent
Expand Down

0 comments on commit b5b5a82

Please sign in to comment.