gpt4 book ai didi

ruby-on-rails - group_by 和计数

转载 作者:行者123 更新时间:2023-12-03 15:59:48 24 4
gpt4 key购买 nike

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

最佳答案

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

关于ruby-on-rails - group_by 和计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6976806/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com