user2669932
user2669932

Reputation: 43

Rails Count and Group to return count and values

Using Ruby 1.9.3.

Assume this example, simple table "cars" in MySQL

id | Model
1  |  Ford
2  |  Ford
3  |  Mini

If I ran this query:

select count(*),model from cars group by model;

I would get

count(*) | model
2        |  Ford
1        |  Mini

Showing me that two entries in the database have the model of "Ford", and one entry has a model of "Mini".

I can't figure out how to get the results of that query in rails (other then using direct SQL to load up an array, etc). Assuming a model called "Car" for table "cars", I've tried things like

Car.find(:all, :select => 'count(*),model', :group => 'model')"

but that just returns the models, not the matching count.

I am looking for a clean method to collect all of the count & model information from the "cars" table that does not require the full direct SQL being used, and then flattening the resulting array to make sense of it. Something elegant. :)

(and if there IS an answer out there already for this question, please just show me where it is. I've searched for a while and all of the questions asked don't seem to fit my bill)

Upvotes: 2

Views: 950

Answers (1)

monteirobrena
monteirobrena

Reputation: 2620

Perhaps this can help you:

Car.all.group(:model).count

And here has other answer that can be useful: rails 3 group by and sum

Upvotes: 1

Related Questions