Skip to content

Instantly share code, notes, and snippets.

@trushkevich
Forked from mrbrdo/rails_group_count.rb
Last active August 29, 2015 14:02
Show Gist options
  • Save trushkevich/3faed6a1f96ed1b9837e to your computer and use it in GitHub Desktop.
Save trushkevich/3faed6a1f96ed1b9837e to your computer and use it in GitHub Desktop.
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.first
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