group_by和count

时间:2011-08-08 00:32:57

标签: ruby-on-rails

@entries_by_source = Entry.joins(:training_entries).group("source_id, classification_id, category_id").select("source_id, classification_id, category_id, count(*) as entries_count")

这些是在@entires_by_source

- !ruby/ActiveRecord:Entry 
  attributes: 
    source_id: 1
    classification_id: 1
    category_id: 1
    entries_count: 198
- !ruby/ActiveRecord:Entry 
  attributes: 
    source_id: 1
    classification_id: 1
    category_id: 2
    entries_count: 614
- !ruby/ActiveRecord:Entry 
  attributes: 
    source_id: 2
    classification_id: 1
    category_id: 3
    entries_count: 1

现在我正在尝试打印这样的东西:

source_id entries_count
1          812 #sum of entries_count 198 + 614
2          1

以下代码无效。任何帮助将不胜感激

<% @entries_by_source.group_by(&:source_id).each do |source_id, entries_count| %>
  <%= source_id %><%= entries_count %>
<% end %>

2 个答案:

答案 0 :(得分:5)

group_by将返回一个类似

的数组

[{'source_id_1' => [values, ...]}, {'source_id_2' => [values, ...]}]

你需要总结一下,例如:

<% @entries_by_source.group_by(&:source_id).each do |source_id, entries| %>
  <%= source_id %><%= entries.sum(&:entries_count) %>
<% end %>

答案 1 :(得分:3)

这里真的很好的例子:http://markusjais.com/the-group_by-method-from-rubys-enumerable-mixin-and-compared-with-scal/

words = ["one", "two", "one", "three", "four", "two", "one"]
count = words.group_by { |w| w }.inject({}) do |tmphash, (k,v)|
      tmphash[k] = v.size
      tmphash
end