如何存储来自每个行具有相同 id 的数据
How to store data from an each where rows has the same id
我是rails开发新手,如果表达不好请见谅
我有一个 rails 每个循环:
r.round_matches.each do |m|
m.round_matches_team.each do |mt|
sheet.add_row [m.round_id, mt.team_name]
end
end
每个round_match有:round_id加倍
输出为:
round_id: 2 team_name: TEST A
round_id: 2 team_name: TEST B
我如何在每个周期中按 id 分组并从 round_match_teams 中分离出每个相同 round_id 的 team_name?我希望我的输出是:
round_id: 2 team_name[1]: TEST A team_name[2]: TEST B
这应该有效
r.round_matches.each do |m|
team_names = m.round_matches_team.map.with_index do |team, index|
"team_name[#{index + 1}]: #{team.team_name}"
end.join(' ')
sheet.add_row ["round_id: #{m.round_id} #{team_names}"]
end
我会以不同的方式处理这个问题:我会以更好的格式处理数据,并根据该数据创建 sheet。
sheet_data = Hash.new([])
r.round_matches.each do |m|
m.round_matches_team.each do |mt|
sheet_data[mt.round_id] << mt.team_name
end
end
sheet_data.each do |round_id, teams|
sheet.add_row [round_id, *teams]
end
解释:我将生成一个散列,其中 round_id
作为键,作为值包含收集的团队名称的数组。然后在添加行时,我使用 splat-operator (*) 来确保每个团队名称将获得一个单独的列。
如果在使用 splat 之前这样做更有意义,您甚至可以对团队名称进行排序,或者不使用 *teams
,而是使用 teams.sort.join(", ")
之类的东西将所有团队合并到一列中(如果 wanted/preferred).
我是rails开发新手,如果表达不好请见谅
我有一个 rails 每个循环:
r.round_matches.each do |m|
m.round_matches_team.each do |mt|
sheet.add_row [m.round_id, mt.team_name]
end
end
每个round_match有:round_id加倍 输出为:
round_id: 2 team_name: TEST A
round_id: 2 team_name: TEST B
我如何在每个周期中按 id 分组并从 round_match_teams 中分离出每个相同 round_id 的 team_name?我希望我的输出是:
round_id: 2 team_name[1]: TEST A team_name[2]: TEST B
这应该有效
r.round_matches.each do |m|
team_names = m.round_matches_team.map.with_index do |team, index|
"team_name[#{index + 1}]: #{team.team_name}"
end.join(' ')
sheet.add_row ["round_id: #{m.round_id} #{team_names}"]
end
我会以不同的方式处理这个问题:我会以更好的格式处理数据,并根据该数据创建 sheet。
sheet_data = Hash.new([])
r.round_matches.each do |m|
m.round_matches_team.each do |mt|
sheet_data[mt.round_id] << mt.team_name
end
end
sheet_data.each do |round_id, teams|
sheet.add_row [round_id, *teams]
end
解释:我将生成一个散列,其中 round_id
作为键,作为值包含收集的团队名称的数组。然后在添加行时,我使用 splat-operator (*) 来确保每个团队名称将获得一个单独的列。
如果在使用 splat 之前这样做更有意义,您甚至可以对团队名称进行排序,或者不使用 *teams
,而是使用 teams.sort.join(", ")
之类的东西将所有团队合并到一列中(如果 wanted/preferred).