我在视图文件的表中显示的记录集合如下所示:
|| user || sport || # of victories || # of losses ||
|| Jane || foo || 1 || 1 ||
|| Jane || foo || 2 || 3 ||
|| Jane || bar || 1 || 1 ||
|| Jane || bar || 2 || 3 ||
在上面的示例中,我尝试根据运动对结果进行分组,而不是拥有2条记录
|| Jane || foo || 1 || 1 ||
|| Jane || foo || 2 || 3 ||
会有一个分组,目前根据我未在此视图上显示的另一列分为多个条目。
|| Jane || foo || 3 || 4 ||
我一直在尝试使用.group和.group_by来完成此操作,但似乎没有正确地执行此操作。有人可以提供一些指示吗?
如果需要,可提供其他信息:
表架构
create_table "records", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|
t.integer "victories"
t.integer "losses"
t.bigint "user_id"
t.bigint "sport_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "opposition_id"
t.index ["opposition_id"], name: "index_records_on_category_id"
t.index ["user_id"], name: "index_records_on_user_id"
end
控制器
def board
@summary = Record.all.sort_by{ |i| i.user_id }
end
查看
<% @summary.each do |record| %>
<tr>
<td><%= record.user.name %></td>
<td><%= record.sport_id %></td>
<td><%= record.victories %></td>
<td><%= record.losses %> </td>
</tr>
<% end %>
答案 0 :(得分:1)
或者使用查询,就像我在视图中放置所有内容一样,但使用控制器来获取数据。
<% sport_records = SportRecord.group(:user_id).select(:user_id, :sport_id, "sum(victories) as total_victories", "sum(losses) as total_losses") %>
<% sport_records.each do |sr| %>
<p><%= sr.sport.name %> | <%= sr.user.name %> | <%= sr.total_victories %> | <%= sr.total_losses %></p>
<% end %>
如果您还需要按运动进行分组,请转到
SportRecord.group(:user_id, :sport_id).select(:user_id, :sport_id, "sum(victories) as total_victories", "sum(losses) as total_losses")