2

Say I have a 'Car' object which contains a 'color' column. I want in my view a listing of color with the number of times it has appeared.

---Car----Color---
Explorer Black
Charger  Yellow
Prius    Black
Jetta    Black
Ferrari  Red 
Pinto    Yellow

In my view, I want:

--Color--Count--
Black      3
Yellow     2
Red        1

In my controller I tried making a list like:

@colorcount = Car.all.count(:group => :color)

and then in my view I have something like

<%= @colorcount.each do |car, count| %>
   <%= car.color %>, <%= count %>
<% end %>

but I'm getting an error like:

undefined method `each' for 0:Fixnum

Is there a lot more to this? Thanks for any help.

1 Answer 1

9
@groups = Car.count(:group=>:color)

<% @groups.each do |color,count| %>
  <%= "#{color}, #{count}" %>
<% end %>
1
  • I was close! The answer that got deleted also worked. Thanks to both of you. I added sorting by this: @groups = Car.count(:group => :color, :order => 'count_all DESC')
    – a3uge
    Jun 3, 2011 at 3:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.