开发者

group_by and count

开发者 https://www.devze.com 2023-03-26 07:22 出处:网络
@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\")
@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
0

精彩评论

暂无评论...
验证码 换一张
取 消