diff --git a/app/models/topic.rb b/app/models/topic.rb index 72818d232db..5ddd18d97a3 100644 --- a/app/models/topic.rb +++ b/app/models/topic.rb @@ -22,11 +22,13 @@ class Topic < ActiveRecord::Base versioned if: :new_version_required? def trash! + update_category_topic_count_by(-1) if deleted_at.nil? super update_flagged_posts_count end def recover! + update_category_topic_count_by(1) unless deleted_at.nil? super update_flagged_posts_count end @@ -630,6 +632,14 @@ class Topic < ActiveRecord::Base def secure_category? category && category.secure end + + private + + def update_category_topic_count_by(num) + if category_id.present? + Category.where(['id = ?', category_id]).update_all("topic_count = topic_count " + (num > 0 ? '+' : '') + "#{num}") + end + end end # == Schema Information diff --git a/spec/models/topic_spec.rb b/spec/models/topic_spec.rb index eea06594468..bb342205640 100644 --- a/spec/models/topic_spec.rb +++ b/spec/models/topic_spec.rb @@ -1293,4 +1293,36 @@ describe Topic do Topic.new(:category => nil).should_not be_secure_category end end + + describe 'trash!' do + context "its category's topic count" do + let(:category) { Fabricate(:category) } + + it "subtracts 1 if topic is being deleted" do + topic = Fabricate(:topic, category: category) + expect { topic.trash! }.to change { category.reload.topic_count }.by(-1) + end + + it "doesn't subtract 1 if topic is already deleted" do + topic = Fabricate(:topic, category: category, deleted_at: 1.day.ago) + expect { topic.trash! }.to_not change { category.reload.topic_count } + end + end + end + + describe 'recover!' do + context "its category's topic count" do + let(:category) { Fabricate(:category) } + + it "adds 1 if topic is deleted" do + topic = Fabricate(:topic, category: category, deleted_at: 1.day.ago) + expect { topic.recover! }.to change { category.reload.topic_count }.by(1) + end + + it "doesn't add 1 if topic is not deleted" do + topic = Fabricate(:topic, category: category) + expect { topic.recover! }.to_not change { category.reload.topic_count } + end + end + end end