Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count group by rows in rails?

When I use User.count(:all, :group => "name"), I get multiple rows, but it's not what I want. What I want is the count of the rows. How can I get it?

like image 520
user199403 Avatar asked Oct 30 '09 03:10

user199403


2 Answers

Currently (18.03.2014 - Rails 4.0.3) this is correct syntax:

Model.group("field_name").count

It returns hash with counts as values e.g.

SurveyReport.find(30).reports.group("status").count

#=> {
  "pdf_generated" => 56
}
like image 53
nothing-special-here Avatar answered Oct 22 '22 00:10

nothing-special-here


  1. User.count will give you the total number of users and translates to the following SQL: SELECT count(*) AS count_all FROM "users"
  2. User.count(:all, :group => 'name') will give you the list of unique names, along with their counts, and translates to this SQL: SELECT count(*) AS count_all, name AS name FROM "users" GROUP BY name

I suspect you want option 1 above, but I'm not clear on what exactly you want/need.

like image 26
hgmnz Avatar answered Oct 22 '22 00:10

hgmnz