一种使用rails列出内容的方法

时间:2013-05-11 07:34:33

标签: ruby ruby-on-rails-3

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

结果图片是:

enter image description here

课程在这里:

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>

1 个答案:

答案 0 :(得分: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 %>