0

现在我正在尝试列出学科等级和版本,但我不知道如何迭代它们):

结果图像是:

在此处输入图像描述

课程在这里:

class Subject

  has_many grades

  has_many versions

end

现在我想在html页面中列出学科等级和版本,html代码在这里:

<div class="row">

  <div class="span12">
    <table class="table table-bordered">

      <tbody>
        <tr  class="success">
          <td rowspan="4" style="text-align: center;vertical-align: middle;">Subject</td>
          <td>Subject1</td>
          <td>Subject2</td>
          <td>Subject3</td>

          <td rowspan="4" style="text-align: center;vertical-align: middle;">Grade</td>
          <td>Grade1</td>

          <td>Grade2</td>
          <td>Grade3</td>
          <td rowspan="4" style="text-align: center;vertical-align: middle;">Version</td>
          <td>Version1</td>
          <td>Version2</td>
          <td>Version3</td>


        </tr>
        <tr  class="success">
          <td>Subject4</td>
          <td>Subject5</td>
          <td>Subject6</td>
          <td>Grade4</td>
          <td>Grade5</td>
          <td>Grade6</td>

          <td>Version4</td>
          <td>Version5</td>
          <td>Version6</td>

        </tr>
        <tr   class="success">

          <td>Subject7</td>
          <td>Subject8</td>
          <td>Subject9</td>
          <td>Grade7</td>
          <td>Grade8</td>
          <td>Grade9</td>

          <td>Version7</td>
          <td>Version8</td>
          <td>Version9</td>

        </tr>
        <tr class="success">

          <td>Subject10</td>
          <td>Subject11</td>
          <td>Subject12</td>
          <td>Grade10</td>
          <td>Grade11</td>
          <td>Grade12</td>

          <td>Version10</td>
          <td>Version11</td>
          <td>Version12</td>

        </tr>

      </tbody>
    </table>
  </div>
</div>
4

1 回答 1

0

这个问题你问了很多,但简单的答案是你需要从 ActiveRecord 中查询所有这些,然后你可以使用任何 Ruby 的内置迭代器,比如Array#each遍历每个迭代器并写出你需要的任何 HTML。

# in the controller...
@subjects = Subject.where(something)
@grades = Grade.where(something)
@versions = Version.where(something)

# in the view (ERB)...
<% @subjects.each do |subject| %>
  <td><%= subject.name %></td>
<% end %>

# in the view (HAML)...
- @subjects.each do |subject|
  %td= subject.name

一些技巧:

如果您绝对必须使用表,则可以使用Array#each_slice对数组进行分区。

# in the view (ERB)...
<% @subjects.each_slice(3) do |slice| %>
  <tr>
  <% slice.each do |subject| %>
    <td><%= subject.name %></td>
  <% end %>
  </tr>
<% end %>
于 2013-05-11T07:59:36.853 回答