From b6de7ad49eb40a108f0776d727ae37adb6f4559e Mon Sep 17 00:00:00 2001
From: Dmitriy Zaporozhets <dmitriy.zaporozhets@gmail.com>
Date: Fri, 18 Sep 2015 10:45:42 +0200
Subject: [PATCH] Fix 500 on trending projects if isntance has 100k+ projects

Signed-off-by: Dmitriy Zaporozhets <dmitriy.zaporozhets@gmail.com>
---
 app/finders/trending_projects_finder.rb   | 17 ++++-------------
 app/views/shared/projects/_list.html.haml |  2 +-
 2 files changed, 5 insertions(+), 14 deletions(-)

diff --git a/app/finders/trending_projects_finder.rb b/app/finders/trending_projects_finder.rb
index f3f4d461efa..9ea342cb26d 100644
--- a/app/finders/trending_projects_finder.rb
+++ b/app/finders/trending_projects_finder.rb
@@ -2,21 +2,12 @@ class TrendingProjectsFinder
   def execute(current_user, start_date = nil)
     start_date ||= Date.today - 1.month
 
+    projects = projects_for(current_user)
+
     # Determine trending projects based on comments count
     # for period of time - ex. month
-    trending_project_ids = Note.
-      select("notes.project_id, count(notes.project_id) as pcount").
-      where('notes.created_at > ?', start_date).
-      group("project_id").
-      reorder("pcount DESC").
-      map(&:project_id)
-
-    sql_order_ids = trending_project_ids.reverse.
-      map { |project_id| "id = #{project_id}" }.join(", ")
-
-    # Get list of projects that user allowed to see
-    projects = projects_for(current_user)
-    projects.where(id: trending_project_ids).reorder(sql_order_ids)
+    projects.joins(:notes).where('notes.created_at > ?', start_date).
+      group("projects.id").reorder("count(notes.id) DESC")
   end
 
   private
diff --git a/app/views/shared/projects/_list.html.haml b/app/views/shared/projects/_list.html.haml
index 021e3b689a1..330b0626d63 100644
--- a/app/views/shared/projects/_list.html.haml
+++ b/app/views/shared/projects/_list.html.haml
@@ -8,7 +8,7 @@
     = render "shared/projects/project", project: project,
       avatar: avatar, stars: stars, css_class: css_class
 
-  - if projects.count > projects_limit
+  - if projects.size > projects_limit
     %li.bottom.center
       .light
         #{projects_limit} of #{pluralize(projects.count, 'project')} displayed.
-- 
GitLab