gpt4 book ai didi

html - Sinatra Ruby 将 SQLite 数据迭代到一个 HTML 列中

转载 作者:行者123 更新时间:2023-12-02 10:52:06 25 4
gpt4 key购买 nike

我的 Sinatra 应用程序中有以下 SQLite 表:

+----------------------------------+
| location area |
+----------------------------------+
| Maine 1 |
| Syracuse 2 |
| Northport 3 |
| NYC 4 |
| Coatesville 4 |
| Erie 4 |
| Dayton 5 |
| Chicago 6 |
| Dallas 6 |
+----------------------------------+

我想根据该数据创建一个如下所示的 HTML 表:

            <table>
<thead>
<tr>
<th>Area 1</th>
<th>Area 2</th>
<th>Area 3</th>
<th>Area 4</th>
<th>Area 5</th>
<th>Area 6</th>
</tr>
</thead>
<tbody>
<tr>
<td>Maine</td>
<td>Syracuse</td>
<td>NorthPort</td>
<td>NYC</td>
<td>Dayton</td>
<td>Chicago</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td>Coatesville</td>
<td></td>
<td>Dallas</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td>Erie</td>
<td></td>
<td></td>
</tr>
</tbody>
</table>

我可以轻松地通过两个嵌套循环迭代每个区域和其中包含的位置,但由于 td 和 tr 在表中的工作方式,我不确定如何将每个区域的位置迭代到单列中

我想我已经把 table 朝下了:

          <thead>
<tr>
<% @table_areas.each do |x| %>
<th><%= x.area %></th>
<% end %>
</tr>
</thead>

但我似乎无法弄清楚其余的事情。每个区域内的区域和位置会经常发生变化,因此我需要动态创建它。

最佳答案

我会这样做:

<% tas = @table_areas.group_by(&:area) %>
<% counter = tas.values.map(&:length).max %>

<table>
<thead>
<tr>
<% tas.keys.each do |x| %>
<th><%= 'Area ' + x.to_s %></th>
<% end %>
</tr>
</thead>
<tbody>
<% (0...counter).each do |i| %>
<tr>
<% tas.values.each do |x| %>
<td><%= x[i] && x[i].location %></td>
<% end %>
</tr>
<% end %>
</tbody>
</table>

如果区号以字符串形式存储在数据库中,您可能需要执行一些 to_i 操作

关于html - Sinatra Ruby 将 SQLite 数据迭代到一个 HTML 列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18050588/

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