FIX: Update topic/post counter correctly when category has zero topics (#8600)

Previously, categories without any topics were being excluded from the UPDATE query. This means the counter gets stuck, and the category cannot be deleted. This change ensures that the counters get correctly set to zero.
This commit is contained in:
David Taylor 2019-12-30 11:20:44 +00:00 committed by GitHub
parent 9348d2cfdf
commit df8444e813
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 25 additions and 4 deletions

View File

@ -188,11 +188,16 @@ class Category < ActiveRecord::Base
DB.exec <<~SQL DB.exec <<~SQL
UPDATE categories c UPDATE categories c
SET topic_count = x.topic_count, SET topic_count = COALESCE(x.topic_count, 0),
post_count = x.post_count post_count = COALESCE(x.post_count, 0)
FROM (#{topics_with_post_count}) x FROM (
SELECT ccc.id as category_id, stats.topic_count, stats.post_count
FROM categories ccc
LEFT JOIN (#{topics_with_post_count}) stats
ON stats.category_id = ccc.id
) x
WHERE x.category_id = c.id WHERE x.category_id = c.id
AND (c.topic_count <> x.topic_count OR c.post_count <> x.post_count) AND (c.topic_count <> COALESCE(x.topic_count, 0) OR c.post_count <> COALESCE(x.post_count, 0))
SQL SQL
# Yes, there are a lot of queries happening below. # Yes, there are a lot of queries happening below.

View File

@ -642,6 +642,22 @@ describe Category do
expect(@uncategorized.posts_week).to eq(1) expect(@uncategorized.posts_week).to eq(1)
end end
end end
context 'when there are no topics left' do
let!(:topic) { create_post(user: @category.user, category: @category.id).reload.topic }
it 'can update the topic count to zero' do
@category.reload
expect(@category.topic_count).to eq(1)
expect(@category.topics.count).to eq(2)
topic.delete # Delete so the post trash/destroy hook doesn't fire
Category.update_stats
@category.reload
expect(@category.topics.count).to eq(1)
expect(@category.topic_count).to eq(0)
end
end
end end
describe "#url" do describe "#url" do