Does the .count.count at the end of this rails3 code look like a typo?
Country.group(:continent).having('sum(population) > 400').count.count
Believe it or not the answer is no. Here’s the set up.
We have a table which looks like this:
mysql> select * from countries;
+-----------------+------------+------------+
| name | population | continent |
+-----------------+------------+------------+
| USA | 300 | America |
| Mexico | 150 | America |
| India | 1200 | Asia |
| Queen Maud Land | 1 | Antarctica |
+-----------------+------------+------------+
And an active record model:
class Country < ActiveRecord::Base
end
Now we want to know how many continents have a combined population above 400. We could write the following rails code:
Country.group(:continent).having('sum(population) > 400').count
Becuase it has both group and count, it means to get the counts for each group. That is, it generates the following SQL:
SELECT COUNT(*) AS count_all, continent AS continent FROM `countries` GROUP BY continent HAVING sum(population) > 400
which returns
+-----------+-----------+
| count_all | continent |
+-----------+-----------+
| 2 | America |
| 1 | Asia |
+-----------+-----------+
which rails turns into:
{"America"=>2, "Asia"=>1}
Now we just need to know how many entries are in this hash. Of course it would work just as well to add .length to the end,
and perhaps that would be clearer, but .count.count is kind of irresistible. So the final query is:
Country.group(:continent).having('sum(population) > 400').count.count