Last active
June 6, 2018 11:29
-
-
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).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
rails 4.0.2
kaminari 0.14.1
Line #8 raises TypeError no implicit conversion of String into Integer so I had to change
to
Also line #14 raises deprecation warning (change scoped to all)