Rails Count and Group to return count and values
Using Rails 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. :)
Anxious for any answers - thank you.
(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)
No comments:
Post a Comment