Skip to content

Instantly share code, notes, and snippets.

@mrstif
Created December 10, 2024 11:48
Show Gist options
  • Save mrstif/65c961a9e31a5350c4e05b718ee380de to your computer and use it in GitHub Desktop.
Save mrstif/65c961a9e31a5350c4e05b718ee380de to your computer and use it in GitHub Desktop.
ActiveAdmin Estimated Counts (with schema handling)
# based on https://medium.com/matic-insurance/how-to-make-ruby-on-rails-activeadmin-and-large-postgresql-tables-friends-again-af199b96f25
module EstimatedCount
extend ActiveSupport::Concern
class_methods do
def estimated_count
query = <<-SQL
select reltuples as estimated_count
from pg_class
INNER JOIN pg_namespace n ON n.oid = pg_class.relnamespace AND nspname = '#{schema_name}'
where relname = '#{table_name_without_schema}'
SQL
result = connection.execute(query).first['estimated_count']
format('%<number>f', number: result).to_i
end
private
def table_name_without_schema
table_name.split('.').last
end
def schema_name
if table_name.include?('.')
table_name.split('.').first
else
'public'
end
end
end
end
module ActiveAdmin
module RenderHelper
def self.sidebar_with_count(dsl)
dsl.sidebar :count, only: :index do
filtered = params[:q].present?
content = filtered ? collection.total_count : "#{collection.estimated_count} (estimated)"
span(content)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment