Skip to content

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

FIX: Serialize categories when viewing a topic (#25206)

Bianca Nenciuc916806fe801
diff --git a/app/assets/javascripts/discourse/app/models/topic.js b/app/assets/javascripts/discourse/app/models/topic.js
index f826ad576b6..f59e5cbcb27 100644
--- a/app/assets/javascripts/discourse/app/models/topic.js
+++ b/app/assets/javascripts/discourse/app/models/topic.js
@@ -36,6 +36,7 @@ export function loadTopicView(topic, args) {
return PreloadStore.getAndRemove(`topic_${topic.id}`, () =>
ajax(jsonUrl, { data })
).then((json) => {
+ json.categories?.forEach((c) => topic.site.updateCategory(c));
topic.updateFromJson(json);
return json;
});
diff --git a/app/serializers/topic_view_serializer.rb b/app/serializers/topic_view_serializer.rb
index e65181b26b5..77364da11be 100644
--- a/app/serializers/topic_view_serializer.rb
+++ b/app/serializers/topic_view_serializer.rb
@@ -83,6 +83,7 @@ class TopicViewSerializer < ApplicationSerializer
has_one :details, serializer: TopicViewDetailsSerializer, root: false, embed: :objects
has_many :pending_posts, serializer: TopicPendingPostSerializer, root: false, embed: :objects
+ has_many :categories, serializer: TopicCategorySerializer, embed: :objects
has_one :published_page, embed: :objects
@@ -316,4 +317,8 @@ class TopicViewSerializer < ApplicationSerializer
def summarizable
object.summarizable?
end
+
+ def include_categories?
+ SiteSetting.lazy_load_categories
+ end
end
diff --git a/lib/topic_view.rb b/lib/topic_view.rb
index f00b64a4771..d52c9f0c37b 100644
--- a/lib/topic_view.rb
+++ b/lib/topic_view.rb
@@ -726,6 +726,12 @@ class TopicView
Summarization::Base.can_see_summary?(@topic, @user)
end
+ def categories
+ categories = [category, category&.parent_category]
+ categories += suggested_topics.categories if suggested_topics
+ categories.compact.uniq
+ end
+
protected
def read_posts_set
diff --git a/spec/requests/topics_controller_spec.rb b/spec/requests/topics_controller_spec.rb
index a27a4c1bd82..181d6a2d530 100644
--- a/spec/requests/topics_controller_spec.rb
+++ b/spec/requests/topics_controller_spec.rb
@@ -3225,6 +3225,20 @@ RSpec.describe TopicsController do
expect(body).to have_tag(:link, with: { itemprop: "image", href: post.image_url })
end
end
+
+ it "returns a list of categories" do
+ SiteSetting.lazy_load_categories = true
+ topic.update!(category: Fabricate(:category))
+ dest_topic.update!(category: Fabricate(:category))
+
+ get "/t/#{topic.slug}/#{topic.id}.json"
+
+ expect(response.parsed_body["categories"].map { |c| c["id"] }).to contain_exactly(
+ SiteSetting.uncategorized_category_id,
+ topic.category_id,
+ dest_topic.category_id,
+ )
+ end
end
describe "#post_ids" do