From 224796a7d42230924af317bafdb78259ed831a1a Mon Sep 17 00:00:00 2001 From: Neil Lalonde Date: Tue, 22 Aug 2017 16:54:28 -0400 Subject: [PATCH] FIX: wrongs counts on tags with deleted topics --- app/models/tag.rb | 6 +++--- spec/models/tag_spec.rb | 11 +++++++++++ 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/app/models/tag.rb b/app/models/tag.rb index 69ab1e65eae..cf965c22d4a 100644 --- a/app/models/tag.rb +++ b/app/models/tag.rb @@ -12,7 +12,7 @@ class Tag < ActiveRecord::Base has_many :tag_group_memberships has_many :tag_groups, through: :tag_group_memberships - COUNT_ARG = "topic_tags.id" + COUNT_ARG = "topics.id" # Apply more activerecord filters to the tags_by_count_query, and then # fetch the result with .count(Tag::COUNT_ARG). @@ -20,9 +20,9 @@ class Tag < ActiveRecord::Base # e.g., Tag.tags_by_count_query.where("topics.category_id = ?", category.id).count(Tag::COUNT_ARG) def self.tags_by_count_query(opts = {}) q = Tag.joins("LEFT JOIN topic_tags ON tags.id = topic_tags.tag_id") - .joins("LEFT JOIN topics ON topics.id = topic_tags.topic_id") + .joins("LEFT JOIN topics ON topics.id = topic_tags.topic_id AND topics.deleted_at IS NULL") .group("tags.id, tags.name") - .order('count_topic_tags_id DESC') + .order('count_topics_id DESC') q = q.limit(opts[:limit]) if opts[:limit] q end diff --git a/spec/models/tag_spec.rb b/spec/models/tag_spec.rb index cf58742fc51..6cea43f3052 100644 --- a/spec/models/tag_spec.rb +++ b/spec/models/tag_spec.rb @@ -46,6 +46,17 @@ describe Tag do counts = described_class.tags_by_count_query.count(Tag::COUNT_ARG) expect(counts[unused.name]).to eq(0) end + + it "doesn't include deleted topics in counts" do + deleted_topic_tag = Fabricate(:tag) + delete_topic = Fabricate(:topic) + post = Fabricate(:post, topic: delete_topic, user: delete_topic.user) + delete_topic.tags << deleted_topic_tag + PostDestroyer.new(Fabricate(:admin), post).destroy + + counts = described_class.tags_by_count_query.count(Tag::COUNT_ARG) + expect(counts[deleted_topic_tag.name]).to eq(0) + end end end