From bafb67f702dd3f6038436e47f80cd18dec9bc0b3 Mon Sep 17 00:00:00 2001 From: Chris Blanchard Date: Sat, 5 Sep 2015 16:23:50 +0100 Subject: [PATCH 1/3] Rewrite recent_topic sql to return unique topics on subquery --- app/models/topic.rb | 9 +++++---- spec/models/topic_spec.rb | 2 +- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/app/models/topic.rb b/app/models/topic.rb index 845d87b..ea3cd43 100644 --- a/app/models/topic.rb +++ b/app/models/topic.rb @@ -43,11 +43,12 @@ class Topic < ActiveRecord::Base def self.recent_topics find_by_sql %q{ - SELECT DISTINCT topics.* - FROM (SELECT id, topic_id + SELECT topics.* + FROM (SELECT max(id) as max_id, topic_id FROM posts - ORDER BY id DESC - LIMIT 20) AS T + GROUP BY topic_id + ORDER BY max_id DESC + LIMIT 10) AS T INNER JOIN topics ON T.topic_id = topics.id INNER JOIN forums diff --git a/spec/models/topic_spec.rb b/spec/models/topic_spec.rb index 718315a..592de27 100644 --- a/spec/models/topic_spec.rb +++ b/spec/models/topic_spec.rb @@ -31,7 +31,7 @@ describe Topic do describe ".recent_topics" do it "returns 5 unique, most recently posted topics" do topics = [] - 6.times do + 10.times do topic = create :topic topics << topic 3.times { create :post, topic: topic } From fc7dd7286efe48465d327a3eff6c162191acfdc7 Mon Sep 17 00:00:00 2001 From: Chris Blanchard Date: Sat, 5 Sep 2015 17:09:20 +0100 Subject: [PATCH 2/3] Return distinct topics --- app/models/topic.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/models/topic.rb b/app/models/topic.rb index ea3cd43..4434206 100644 --- a/app/models/topic.rb +++ b/app/models/topic.rb @@ -43,7 +43,7 @@ class Topic < ActiveRecord::Base def self.recent_topics find_by_sql %q{ - SELECT topics.* + SELECT DISTINCT topics.* FROM (SELECT max(id) as max_id, topic_id FROM posts GROUP BY topic_id From d4db1aafdfd55f88a1ee62adae826dc726362914 Mon Sep 17 00:00:00 2001 From: Chris Blanchard Date: Sat, 5 Sep 2015 19:16:14 +0100 Subject: [PATCH 3/3] Limit by 200 --- app/models/topic.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/models/topic.rb b/app/models/topic.rb index 4434206..464ad29 100644 --- a/app/models/topic.rb +++ b/app/models/topic.rb @@ -48,7 +48,7 @@ class Topic < ActiveRecord::Base FROM posts GROUP BY topic_id ORDER BY max_id DESC - LIMIT 10) AS T + LIMIT 200) AS T INNER JOIN topics ON T.topic_id = topics.id INNER JOIN forums