From c60668a0521f1eb2f95cf4c3c594cc2f75293b1c Mon Sep 17 00:00:00 2001 From: David Taylor Date: Thu, 15 Apr 2021 11:05:03 +0100 Subject: [PATCH] FIX: Ensure the top 6 categories are shown in the user summary (#12691) Previously it would pluck 6 categories which the user had posted in, **then** order them. To select the **top 6** categories, we need to perform the ordering in the SQL query before the LIMIT --- app/models/user_summary.rb | 2 +- spec/models/user_summary_spec.rb | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/app/models/user_summary.rb b/app/models/user_summary.rb index 627733e062e..69796d9fc1a 100644 --- a/app/models/user_summary.rb +++ b/app/models/user_summary.rb @@ -145,7 +145,7 @@ class UserSummary top_categories = {} - Category.where(id: post_count_query.limit(MAX_SUMMARY_RESULTS).pluck('category_id')) + Category.where(id: post_count_query.order("count(*) DESC").limit(MAX_SUMMARY_RESULTS).pluck('category_id')) .pluck(:id, :name, :color, :text_color, :slug, :read_restricted, :parent_category_id) .each do |c| top_categories[c[0].to_i] = CategoryWithCounts.new( diff --git a/spec/models/user_summary_spec.rb b/spec/models/user_summary_spec.rb index 791e61b6e1c..8847fc2a3a0 100644 --- a/spec/models/user_summary_spec.rb +++ b/spec/models/user_summary_spec.rb @@ -58,4 +58,24 @@ describe UserSummary do users = UserSummary.new(user, Guardian.new).most_liked_users expect(users).to eq([]) end + + it "includes ordered top categories" do + u = Fabricate(:user) + + UserSummary::MAX_SUMMARY_RESULTS.times do + c = Fabricate(:category) + t = Fabricate(:topic, category: c, user: u) + Fabricate(:post, user: u, topic: t) + end + + top_category = Fabricate(:category) + t = Fabricate(:topic, category: top_category, user: u) + Fabricate(:post, user: u, topic: t) + Fabricate(:post, user: u, topic: t) + + summary = UserSummary.new(u, Guardian.new) + + expect(summary.top_categories.length).to eq(UserSummary::MAX_SUMMARY_RESULTS) + expect(summary.top_categories.first[:id]).to eq(top_category.id) + end end