Add filter to recent topics

This commit is contained in:
Chris Blanchard 2015-08-22 10:48:08 +01:00
parent d26305b523
commit 23b60878e4
3 changed files with 23 additions and 15 deletions

View file

@ -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

View file

@ -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|

View file

@ -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"