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

When navigating straight to a topic the category was not displayed at
all because the categories were not loaded. Similarly, the categories
for suggested topics were not loaded either.

This commit adds a list of categories to topic view model class and
serializer.
This commit is contained in:
Bianca Nenciu 2024-01-10 20:30:59 +02:00 committed by GitHub
parent 0d52331823
commit c916806fe8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 26 additions and 0 deletions

View File

@ -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;
});

View File

@ -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

View File

@ -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

View File

@ -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