Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")

These 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 %>
like image 331
danke Avatar asked Feb 23 '23 08:02

danke


2 Answers

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
like image 33
Richard Peck Avatar answered Feb 27 '23 21:02

Richard Peck


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 %>
like image 68
numbers1311407 Avatar answered Feb 27 '23 21:02

numbers1311407