Skip to content

Instantly share code, notes, and snippets.

@mrbrdo
Last active June 6, 2018 11:29
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mrbrdo/5679455 to your computer and use it in GitHub Desktop.
Save mrbrdo/5679455 to your computer and use it in GitHub Desktop.
Rails ActiveRecord / ActiveRelation grouped count as integer (sum of counts for each group). Tested on Postgres This can be used for Kaminari too (speeds up total_pages and total_count considerably).
module ActiveRecordGroupCount
extend ActiveSupport::Concern
module ExtensionMethods
def count(*args)
scope = except(:select).select("1")
query = "SELECT count(*) AS count_all FROM (#{scope.to_sql}) x"
ActiveRecord::Base.connection.execute(query).first.try(:[], "count_all").to_i
end
end
module ClassMethods
def returns_count_sum
scoped.extending(ExtensionMethods)
end
end
end
ActiveRecord::Base.send :include, ActiveRecordGroupCount
# usage:
# Model.group(:something).returns_count_sum.count
# faster Kaminari pagination:
# Model.returns_count_sum.page(1).per(10).total_pages
@trushkevich
Copy link

rails 4.0.2
kaminari 0.14.1

Line #8 raises TypeError no implicit conversion of String into Integer so I had to change

ActiveRecord::Base.connection.execute(query).first.try(:[], "count_all").to_i

to

ActiveRecord::Base.connection.execute(query).first.first

Also line #14 raises deprecation warning (change scoped to all)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment