How to simulate ActiveRecord Model.count.to_sql
You may want to dip into Arel:
Model.select(Arel.star.count).to_sql
ASIDE:I find I often want to find sub counts, so I embed the count(*) into another query:
child_counts = ChildModel.select(Arel.star.count) .where(Model.arel_attribute(:id).eq( ChildModel.arel_attribute(:model_id)))Model.select(Arel.star).select(child_counts.as("child_count")) .order(:id).limit(10).to_sql
which then gives you all the child counts for each of the models:
SELECT *, ( SELECT COUNT(*) FROM "child_models" WHERE "models"."id" = "child_models"."model_id" ) child_countFROM "models"ORDER BY "models"."id" ASCLIMIT 10
Best of luck