diff --git a/app/serializers/topic_view_serializer.rb b/app/serializers/topic_view_serializer.rb index 4a381bea7ef..9f6ea937e8b 100644 --- a/app/serializers/topic_view_serializer.rb +++ b/app/serializers/topic_view_serializer.rb @@ -279,7 +279,7 @@ class TopicViewSerializer < ApplicationSerializer end def participant_count - object.participants.size + object.participant_count end private diff --git a/lib/topic_view.rb b/lib/topic_view.rb index b45b6cfe213..d582b4a5e2d 100644 --- a/lib/topic_view.rb +++ b/lib/topic_view.rb @@ -275,9 +275,11 @@ class TopicView end end + MAX_PARTICIPANTS = 24 + def post_counts_by_user @post_counts_by_user ||= begin - post_ids = unfiltered_posts.pluck(:id) + post_ids = unfiltered_post_ids return {} if post_ids.blank? @@ -288,13 +290,30 @@ class TopicView AND user_id IS NOT NULL GROUP BY user_id ORDER BY count_all DESC - LIMIT 24 + LIMIT #{MAX_PARTICIPANTS} SQL Hash[Post.exec_sql(sql, post_ids: post_ids).values] end end + def participant_count + @participant_count ||= + begin + if participants.size == MAX_PARTICIPANTS + sql = <<~SQL + SELECT COUNT(DISTINCT user_id) + FROM posts + WHERE id IN (:post_ids) + AND user_id IS NOT NULL + SQL + Post.exec_sql(sql, post_ids: unfiltered_post_ids).getvalue(0, 0).to_i + else + participants.size + end + end + end + def participants @participants ||= begin participants = {} @@ -354,6 +373,17 @@ class TopicView @filtered_post_ids ||= filtered_post_stream.map { |tuple| tuple[0] } end + def unfiltered_post_ids + @unfiltered_post_ids ||= + begin + if @contains_gaps + unfiltered_post.pluck(:id) + else + filtered_post_ids + end + end + end + protected def read_posts_set