Using more activerecord instead of pure sql.
Fix issue where count queries would explode.

Only applied to Rails master branch.