What's the right way to do counts in Rails? What's the right way to do counts in Rails? sql sql

What's the right way to do counts in Rails?


You don't need a name scope to perform a count.

Account.where(:admin => false).count

But named scopes are an excellent way to make your code more reusable.

Named scopes don't have any noticeable performance impact on your application.


I would recommend you to avoid direct access to database in my templates because then you're losing a bit of flexibility when it comes to caching.

Try to prepare all the data you need to render in your action instead and then use meaningful instance variables like @number_of_accounts or @accounts.count.

This will make your views cleaner and easier to debug and also a bit more DRY if you render action in different formats (html, json, etc)

As to how do you get your numbers - it doesn't really matter that much, just move away from find_* methods towards scoping and write readable code


In rails 3 a simple call to count issues a simple count request:

Contact.count

is resolved as:

SELECT COUNT(*) AS count_id FROM "contacts"

a find all by field name will resolve as:

Contact.find_all_by_country("Canada")SELECT "contacts".* FROM "contacts" WHERE ("contacts"."country" = 'Canada')

I would recommend indexing your admin column for faster lookups and this can be translated into a named scope, but that by itself will only predefine the query, not optimize it.

It is important to note that if you issue

Contact.find_all_by_country("Canada").count

count is a method on the array class and doesn't actually issue a count on the database:

Contact.find_all_by_country("Canada").countSELECT "contacts".* FROM "contacts" WHERE ("contacts"."country" = 'Canada')