group_by and count
@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")
Th开发者_运维问答ese are in @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
Now i'm trying to print something like that:
source_id entries_count
1 812 #sum of entries_count 198 + 614
2 1
The code below is not working. Any help will be appreciated
<% @entries_by_source.group_by(&:source_id).each do |source_id, entries_count| %>
<%= source_id %><%= entries_count %>
<% end %>
group_by would return an array like
[{'source_id_1' => [values, ...]}, {'source_id_2' => [values, ...]}]
You'd need to sum the count, something like:
<% @entries_by_source.group_by(&:source_id).each do |source_id, entries| %>
<%= source_id %><%= entries.sum(&:entries_count) %>
<% end %>
Really good example here: 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
精彩评论