From 49b5d66a327313ec3b80316ea8c2c46242168ca4 Mon Sep 17 00:00:00 2001 From: Sarah Ridge Date: Fri, 2 Dec 2022 21:47:10 -0500 Subject: [PATCH 1/2] Fix records_count when using group by --- lib/geared_pagination/recordset.rb | 2 +- test/recordset_test.rb | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/geared_pagination/recordset.rb b/lib/geared_pagination/recordset.rb index 2981a96..4c9d682 100644 --- a/lib/geared_pagination/recordset.rb +++ b/lib/geared_pagination/recordset.rb @@ -32,7 +32,7 @@ def page_count end def records_count - @records_count ||= records.unscope(:limit).unscope(:offset).unscope(:select).count + @records_count ||= records.unscope(:limit).unscope(:offset).unscope(:select).to_a.size end private diff --git a/test/recordset_test.rb b/test/recordset_test.rb index 4dc66e4..8b93b40 100644 --- a/test/recordset_test.rb +++ b/test/recordset_test.rb @@ -76,4 +76,10 @@ class GearedPagination::RecordsetTest < ActiveSupport::TestCase recordset = GearedPagination::Recordset.new(select_scoped_records, per_page: [ 10, 15, 20 ]) assert_equal Recording.all.count, recordset.records_count end + + test "records count for group by" do + select_scoped_records = Recording.all.select(:id, :number).group(:id) + recordset = GearedPagination::Recordset.new(select_scoped_records, per_page: [ 10, 15, 20 ]) + assert_equal Recording.all.count, recordset.records_count + end end From fce042de5ecb486bba9f06d1270596ac4c488698 Mon Sep 17 00:00:00 2001 From: Sarah Ridge Date: Wed, 1 Nov 2023 21:33:21 -0400 Subject: [PATCH 2/2] Fix performance by avoiding array conversion --- lib/geared_pagination/recordset.rb | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/geared_pagination/recordset.rb b/lib/geared_pagination/recordset.rb index 4c9d682..96262d3 100644 --- a/lib/geared_pagination/recordset.rb +++ b/lib/geared_pagination/recordset.rb @@ -32,7 +32,13 @@ def page_count end def records_count - @records_count ||= records.unscope(:limit).unscope(:offset).unscope(:select).to_a.size + if @records_count.nil? + @records_count = records.unscope(:limit).unscope(:offset).unscope(:select).size + # records count could be a hash if query has a group by clause -> in this case records count is number of groups + @records_count = @records_count.size if @records_count.is_a?(Hash) + end + + @records_count end private