From 67041d1c6dfa27872bbc713c7f79e3f57e1dbb23 Mon Sep 17 00:00:00 2001 From: Robin Ward Date: Thu, 14 Nov 2013 14:32:41 -0500 Subject: [PATCH] Support for tracking the count of unique participants in a topic --- app/models/topic_featured_users.rb | 11 +++++-- ...4185225_add_participant_count_to_topics.rb | 13 +++++++++ spec/jobs/feature_topic_users_spec.rb | 29 +++++++++++++++++++ 3 files changed, 50 insertions(+), 3 deletions(-) create mode 100644 db/migrate/20131114185225_add_participant_count_to_topics.rb diff --git a/app/models/topic_featured_users.rb b/app/models/topic_featured_users.rb index 6a0c0a491c8..fe6533a5580 100644 --- a/app/models/topic_featured_users.rb +++ b/app/models/topic_featured_users.rb @@ -14,13 +14,14 @@ class TopicFeaturedUsers topic.reload unless rails4? clear update keys(args) + update_participant_count topic.save end def user_ids - [topic.featured_user1_id, - topic.featured_user2_id, - topic.featured_user3_id, + [topic.featured_user1_id, + topic.featured_user2_id, + topic.featured_user3_id, topic.featured_user4_id].uniq.compact end @@ -48,4 +49,8 @@ class TopicFeaturedUsers topic.send("featured_user#{i+1}_id=", user_id) end end + + def update_participant_count + topic.participant_count = topic.posts.count('distinct user_id') + end end diff --git a/db/migrate/20131114185225_add_participant_count_to_topics.rb b/db/migrate/20131114185225_add_participant_count_to_topics.rb new file mode 100644 index 00000000000..20983e64d93 --- /dev/null +++ b/db/migrate/20131114185225_add_participant_count_to_topics.rb @@ -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 diff --git a/spec/jobs/feature_topic_users_spec.rb b/spec/jobs/feature_topic_users_spec.rb index cea64c128f6..36c7db9aa09 100644 --- a/spec/jobs/feature_topic_users_spec.rb +++ b/spec/jobs/feature_topic_users_spec.rb @@ -42,4 +42,33 @@ describe Jobs::FeatureTopicUsers do 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