From 4377d070951e42f5dfb3b20c2d8ffb3ad64237a7 Mon Sep 17 00:00:00 2001 From: Chris Blanchard Date: Sat, 22 Aug 2015 10:48:08 +0100 Subject: [PATCH] Add filter to recent topics --- app/models/topic.rb | 23 +++++++++++++++-------- spec/factories/topic.rb | 2 +- spec/models/topic_spec.rb | 13 +++++++------ 3 files changed, 23 insertions(+), 15 deletions(-) diff --git a/app/models/topic.rb b/app/models/topic.rb index d1b1fe1..deb1cdb 100644 --- a/app/models/topic.rb +++ b/app/models/topic.rb @@ -42,14 +42,21 @@ class Topic < ActiveRecord::Base acts_as_readable def self.recent_topics - Post.joins("LEFT OUTER JOIN topics ON topics.id = posts.topic_id"). - joins("LEFT OUTER JOIN forums on forums.id = topics.forum_id"). - joins("LEFT OUTER JOIN forumers on forums.id = forumers.forum_id"). - order("posts.id desc"). - where("forumers.id IS NULL"). - select("DISTINCT topic_id"). - limit(5). - map(&:topic) + self.find_by_sql %q{ + SELECT DISTINCT topics.* + FROM (SELECT id, topic_id + FROM posts + ORDER BY id DESC + LIMIT 20) AS T + INNER JOIN topics + ON T.topic_id = topics.id + INNER JOIN forums + ON forums.id = topics.forum_id + LEFT OUTER JOIN forumers + ON forumers.forum_id = forums.id + WHERE forumers.id IS NULL + LIMIT 5 + } end def to_s diff --git a/spec/factories/topic.rb b/spec/factories/topic.rb index 39637c0..fde6d83 100644 --- a/spec/factories/topic.rb +++ b/spec/factories/topic.rb @@ -1,6 +1,6 @@ FactoryGirl.define do factory :topic do - sequence(:title) { |n| "Forum Title #{n}" } + sequence(:title) { |n| "Topic Title #{n}" } forum user before(:create) do |topic| diff --git a/spec/models/topic_spec.rb b/spec/models/topic_spec.rb index e9f740c..718315a 100644 --- a/spec/models/topic_spec.rb +++ b/spec/models/topic_spec.rb @@ -29,16 +29,17 @@ describe Topic do end describe ".recent_topics" do - before(:each) do - 5.times do + it "returns 5 unique, most recently posted topics" do + topics = [] + 6.times do topic = create :topic + topics << topic 3.times { create :post, topic: topic } end - end - it "returns 5 unique, most recently posted topics" do recent_topics = Topic.recent_topics - expect(recent_topics.length).to eq(5) - expect(recent_topics.map(&:id).uniq.length).to eq(5) + topics.last(5).each do |topic| + expect(recent_topics).to include(topic) + end end it "does not return posts from restricted forums" do restricted_topic = create :topic, title: "Restricted"