diff --git a/app/services/analytics_service.rb b/app/services/analytics_service.rb index da70c268d..2860eef44 100644 --- a/app/services/analytics_service.rb +++ b/app/services/analytics_service.rb @@ -54,7 +54,11 @@ class AnalyticsService # Returns the list of referrers def referrers(top: 20) # count_all is the name of the field autogenerated by Rails with COUNT(*) - counts = page_view_data.group(:domain).order(count_all: :desc).limit(top).count + counts = page_view_data + .group(:domain) + .order(Arel.sql("sum_counts_for_number_of_views DESC")) + .limit(top) + .sum("counts_for_number_of_views") # we transform this in a list of hashes in case we need to add more keys domains = counts.map { |domain, count| { domain: domain, count: count } } diff --git a/spec/services/analytics_service_spec.rb b/spec/services/analytics_service_spec.rb index aef1c3df1..cb59e5135 100644 --- a/spec/services/analytics_service_spec.rb +++ b/spec/services/analytics_service_spec.rb @@ -410,14 +410,14 @@ RSpec.describe AnalyticsService, type: :service do expect(analytics_service.referrers[:domains]).to be_empty end - it "returns the domains ordered by count" do + it "returns the domains ordered by number of views" do other_url = Faker::Internet.url create_list(:page_view, 2, user: user, article: article, referrer: other_url) top_url = Faker::Internet.url - create_list(:page_view, 3, user: user, article: article, referrer: top_url) + create_list(:page_view, 3, user: user, article: article, referrer: top_url, counts_for_number_of_views: 10) expected_result = [ - { domain: Addressable::URI.parse(top_url).domain, count: 3 }, + { domain: Addressable::URI.parse(top_url).domain, count: 30 }, { domain: Addressable::URI.parse(other_url).domain, count: 2 }, ] expect(analytics_service.referrers[:domains]).to eq(expected_result)