Support for tracking the count of unique participants in a topic

This commit is contained in:
Robin Ward 2013-11-14 14:32:41 -05:00
parent 41dfcd2774
commit 67041d1c6d
3 changed files with 50 additions and 3 deletions

View File

@ -14,13 +14,14 @@ class TopicFeaturedUsers
topic.reload unless rails4? topic.reload unless rails4?
clear clear
update keys(args) update keys(args)
update_participant_count
topic.save topic.save
end end
def user_ids def user_ids
[topic.featured_user1_id, [topic.featured_user1_id,
topic.featured_user2_id, topic.featured_user2_id,
topic.featured_user3_id, topic.featured_user3_id,
topic.featured_user4_id].uniq.compact topic.featured_user4_id].uniq.compact
end end
@ -48,4 +49,8 @@ class TopicFeaturedUsers
topic.send("featured_user#{i+1}_id=", user_id) topic.send("featured_user#{i+1}_id=", user_id)
end end
end end
def update_participant_count
topic.participant_count = topic.posts.count('distinct user_id')
end
end end

View File

@ -0,0 +1,13 @@
class AddParticipantCountToTopics < ActiveRecord::Migration
def up
add_column :topics, :participant_count, :integer, default: 1
execute "UPDATE topics SET participant_count =
(SELECT COUNT(DISTINCT p.user_id) FROM posts AS p WHERE p.topic_id = topics.id)"
end
def down
remove_column :topics, :participant_count
end
end

View File

@ -42,4 +42,33 @@ describe Jobs::FeatureTopicUsers do
end end
context "participant count" do
let!(:post) { create_post }
let(:topic) { post.topic }
it "it works as expected" do
# It has 1 participant after creation
topic.participant_count.should == 1
# It still has 1 after featuring
Jobs::FeatureTopicUsers.new.execute(topic_id: topic.id)
topic.reload.participant_count.should == 1
# If the OP makes another post, it's still 1.
create_post(topic: topic, user: post.user)
Jobs::FeatureTopicUsers.new.execute(topic_id: topic.id)
topic.reload.participant_count.should == 1
# If another users posts, it's 2.
create_post(topic: topic, user: Fabricate(:evil_trout))
Jobs::FeatureTopicUsers.new.execute(topic_id: topic.id)
topic.reload.participant_count.should == 2
end
end
end end