Add more efficient recent topics class method

This commit is contained in:
Chris Blanchard 2015-08-20 16:20:40 +01:00
parent f20d5294b9
commit 46b0084e81
2 changed files with 20 additions and 0 deletions

View file

@ -47,6 +47,10 @@ class Topic < ActiveRecord::Base
acts_as_readable
def self.recent_topics
Post.order('id desc').select('DISTINCT topic_id').limit(5).map(&:topic)
end
def to_s
title
end

View file

@ -27,4 +27,20 @@ describe Topic do
end.to change(Topic, :count).by(1)
end
end
describe ".recent_topics" do
before(:all) do
5.times do
topic = create :topic
3.times do
post = create :post, topic: topic
end
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)
end
end
end