2

想知道将视图中模型上的循环拆分到两个表上的最佳方法是什么。看起来很简单。

   <div>
        <table>
          <tr><th>Refreshments and Exhibits</th></tr>
          <% @exhibitor.each do |exhibitor| %>
          <tr>
            <td><%= exhibitor.name %></td>
          </tr>
        <% end %>
        </table>
    </div>
    <div>
        <table>
          <tr><th>Refreshments and Exhibits</th></tr>
          <% @exhibitor.each do |exhibitor| %>
          <tr>
            <td><%= exhibitor.name %></td>
          </tr>
        <% end %>
        </table>
     </div>

这将显示同一张表两次。我想循环遍历@exhibitor 以填充第一个表中的 td,限制为 15。然后继续循环遍历第二个表的其余部分。

4

1 回答 1

3

如果你想要 15 桌,请执行此操作

<% @exhibitors.each_slice(15) do |exhibitors_group| %>
  <div>
    <table>
      <tr><th>Refreshments and Exhibits</th></tr>
      <% exhibitors_group.each do |exhibitor| %>
        <tr>
          <td><%= exhibitor.name %></td>
        </tr>
      <% end %>
    </table>
  </div>
<% end %>

如果您想要前 15 个和其他表中的其余部分,请执行此操作

  <div>
    <table>
      <tr><th>Refreshments and Exhibits</th></tr>
      <% @exhibitor[0..15].each do |exhibitor| %>
        <tr>
          <td><%= exhibitor.name %></td>
        </tr>
      <% end %>
    </table>
  </div>


  <div>
    <table>
      <tr><th>Refreshments and Exhibits</th></tr>
      <% @exhibitors[16..-1].each do |exhibitor| %>
        <tr>
          <td><%= exhibitor.name %></td>
        </tr>
      <% end %>
    </table>
  </div>

您还应该考虑两件事:

  • 为这些表使用助手或布局
  • 而不是在视图中对数组进行切片,而是在控制器中进行
于 2012-12-28T01:20:29.030 回答