Improved total_count for groups

This is a part of code snippet in the Kaminari.

Someone submit the pull request and Can you explain this change of the code?

Do you want to accept this pull request or not?

If you want to accept this pull request, please select the "Solution B", if not select the "Solution A".

Solution A
# frozen_string_literal: true
module Kaminari
  module ActiveRecordRelationMethods
    def entry_name(options = {})
      default = options[:count] == 1 ? model_name.human : model_name.human.pluralize
      model_name.human(options.reverse_merge(default: default))
    end
    def reset #:nodoc:
      @total_count = nil
      super
    end
    def total_count(column_name = :all, _options = nil) #:nodoc:
      # #count overrides the #select which could include generated columns referenced in #order, so skip #order here, where it's irrelevant to the result anyway
      @total_count ||= begin
        c = except(:offset, :limit, :order)
        # Remove includes only if they are irrelevant
        c = c.except(:includes) unless references_eager_loaded_tables?
        # .group returns an OrderedHash that responds to #count
        c = c.count(column_name)
        if c.is_a?(Hash) || c.is_a?(ActiveSupport::OrderedHash)
          c.count
        else
          c.respond_to?(:count) ? c.count(column_name) : c
        end
      end
    end
  end
end
 
Solution B
         # Remove includes only if they are irrelevant
         c = c.except(:includes) unless references_eager_loaded_tables?
 
-        # .group returns an OrderedHash that responds to #count
-        c = c.count(column_name)
+        # it covers the common case
+        if column_name == :all &&  c.group_values.any?
+          # count with group is just a distinct count by group value
+          c = c.except(:group, :select).select(c.group_values).distinct.count
+        else
+          # .group returns an OrderedHash that responds to #count
+          c = c.count(column_name)
+        end
+
         if c.is_a?(Hash) || c.is_a?(ActiveSupport::OrderedHash)
           c.count
         else
 
Log in to accept this challenge