2011-08-08 64 views
4
@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_sourceGROUP_BY和計數

- !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 %> 

回答

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 %> 
+0

謝謝先生...... – danke