Skip to content

A platform for community discussion. Free, open, simple.

PERF: Avoid running the same query twice in `TopicViewSerializer#details`.

Guo Xiang Tan3bfd9698c720
diff --git a/app/models/topic.rb b/app/models/topic.rb
index 369d0e3367a..ede59422bd9 100644
--- a/app/models/topic.rb
+++ b/app/models/topic.rb
@@ -446,6 +446,7 @@ class Topic < ActiveRecord::Base
@post_numbers = nil
@public_topic_timer = nil
@private_topic_timer = nil
+ @is_category_topic = nil
super(options)
end
@@ -1347,6 +1348,10 @@ SQL
private_messages.with_subtype(topic_subtype).where('topics.created_at >= ? AND topics.created_at <= ?', start_date, end_date).group('date(topics.created_at)').order('date(topics.created_at)').count
end
+ def is_category_topic?
+ @is_category_topic ||= Category.exists?(topic_id: self.id.to_i)
+ end
+
private
def update_category_topic_count_by(num)
diff --git a/lib/guardian/topic_guardian.rb b/lib/guardian/topic_guardian.rb
index 0d75e290d87..d3b60521806 100644
--- a/lib/guardian/topic_guardian.rb
+++ b/lib/guardian/topic_guardian.rb
@@ -86,15 +86,15 @@ module TopicGuardian
def can_delete_topic?(topic)
!topic.trashed? &&
is_staff? &&
- !(Category.exists?(topic_id: topic.id)) &&
+ !(topic.is_category_topic?) &&
!Discourse.static_doc_topic_ids.include?(topic.id)
end
def can_convert_topic?(topic)
return false unless SiteSetting.enable_personal_messages?
return false if topic.blank?
- return false if topic && topic.trashed?
- return false if Category.where("topic_id = ?", topic.id).exists?
+ return false if topic.trashed?
+ return false if topic.is_category_topic?
return true if is_admin?
is_moderator? && can_create_post?(topic)
end