如何将组合数组列表转换为HTML表格?字段映射问题
解决方案:将车队车手组合渲染为HTML表格
你的核心问题是控制器输出的哈希结构和视图期望的键不匹配——当前@combo的每个元素是单键哈希(键是空格分隔的车队+车手字符串,值是包含价格和积分的子哈希),而视图里直接用:team、:drivers这类键自然取不到数据。下面提供两种解决方式:
方式1:修改控制器生成结构化哈希(推荐)
直接在控制器里拆分组合数组,生成包含明确字段的哈希,让视图逻辑更清晰:
# OUTPUT output = ordered.map do |c| # c数组结构为 [车队, 积分翻倍车手, 车手1, 车手2] team = c[0] double_driver = c[1] regular_drivers = c[2..3].join(", ") # 两名普通车手用逗号分隔展示 { team: team, double: double_driver, drivers: regular_drivers, price: add_up(c, team_price, driver_price), points: add_dbl(c, team_points, driver_points).round(2) } end @combo = output
修改后,视图只需微调键名即可正常渲染:
<table class="table table-condensed"> <thead> <tr> <th>Team</th> <th>Drivers</th> <th>Double</th> <th>Price</th> <th>Points</th> </tr> </thead> <tbody> <% @combo.each do |mycombo| %> <tr> <td><%= mycombo[:team] %></td> <td><%= mycombo[:drivers] %></td> <td><%= mycombo[:double] %></td> <td><%= mycombo[:price] %></td> <td><%= mycombo[:points] %></td> </tr> <% end %> </tbody> </table>
方式2:在视图中直接解析现有结构
如果不想修改控制器,可以在视图里拆分每个组合的字符串键,提取所需数据:
<table class="table table-condensed"> <thead> <tr> <th>Team</th> <th>Drivers</th> <th>Double</th> <th>Price</th> <th>Points</th> </tr> </thead> <tbody> <% @combo.each do |mycombo| %> <% # 取出单键哈希的组合字符串和价格积分数据 %> <% combo_string, stats = mycombo.first %> <% # 拆分字符串为车队、翻倍车手、普通车手 %> <% team, double_driver, driver1, driver2 = combo_string.split(" ") %> <tr> <td><%= team %></td> <td><%= "#{driver1}, #{driver2}" %></td> <td><%= double_driver %></td> <td><%= stats[:price] %></td> <td><%= stats[:points] %></td> </tr> <% end %> </tbody> </table>
注意事项
- 需确保
ordered数组里的每个c元素结构固定为[车队, 积分翻倍车手, 车手1, 车手2],否则拆分逻辑会出错。 - 方式1的结构化哈希更易于维护和扩展,后续添加新字段只需在控制器补充即可。
内容的提问来源于stack exchange,提问作者ldthompson
相关产品推荐
相关产品推荐

