a3u*_*uge 2 ruby grouping ruby-on-rails count ruby-on-rails-3
假设我有一个'Car'对象,其中包含'color'列.在我的视图中,我想要一个颜色列表及其出现的次数.
---Car----Color---
Explorer Black
Charger Yellow
Prius Black
Jetta Black
Ferrari Red
Pinto Yellow
Run Code Online (Sandbox Code Playgroud)
在我看来,我想:
--Color--Count--
Black 3
Yellow 2
Red 1
Run Code Online (Sandbox Code Playgroud)
在我的控制器中,我尝试制作如下列表:
@colorcount = Car.all.count(:group => :color)
Run Code Online (Sandbox Code Playgroud)
然后在我看来我有类似的东西
<%= @colorcount.each do |car, count| %>
<%= car.color %>, <%= count %>
<% end %>
Run Code Online (Sandbox Code Playgroud)
但我收到的错误如下:
undefined method `each' for 0:Fixnum
Run Code Online (Sandbox Code Playgroud)
还有更多吗?谢谢你的帮助.
@groups = Car.count(:group=>:color)
<% @groups.each do |color,count| %>
<%= "#{color}, #{count}" %>
<% end %>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3539 次 |
| 最近记录: |