如何创建 non-static HTML table header 和行

How to create a non-static HTML table header and rows

我有两个数组,我想用动态 header 单元格(来自第一个名为 subjects 的数组)创建一个 table 并迭代添加内容(来自第二个数组 examscores) 在 table 行中相对于 table header 值。

期望的结果是 (fiddle):

erb代码是:

 <table width="100%" border="1">
 <thead>
 <tr>
 <th rowspan="2" scope="col">NAME</th>
 <th colspan="<%= @subjects_by_class.size %>" scope="col">Subjects/Scores</th>
 <th rowspan="2" scope="col">Total</th>
 <th rowspan="2" scope="col">Average</th>
 </tr>
 <tr>
 <% @subjects_by_class.each do |s| %>
 <th> <%= s.name %></th>
 <% end %>
 </tr>
 </thead>
 <tbody>
 <% @examscore.each do |ex| %>
 <tr>

 <td><%= get_student_name_by_id(ex.student_id) %></td>

 <% @subjects_by_class.each do |ss| %>
 <% @examscore.each do |ii| %>

 <% if ss.id == ex.subject_id %>
 <td> <%= i.total %> </td>
 <% break %>
 <% end %>

 <% end %>
 <% end %>

 <td><%= sum_student_totalscore(ex.student_id, year_id) %> </td>
 <td><%= avg_student_totalscore(ex.student_id, year_id) %></td>
 </tr>
 <% end %>
 </tbody>
 </table>

我得到的输出是 (fiddle):

Maths 主题下创建了一个新的 tr,而不是为 Arts 主题创建了一个新的 td,这导致 Average td 被扭曲。

任何见解将不胜感激。

好吧,看看你的这部分代码:

<% @examscore.each do |ex| %>
 <tr>

您为每个@examscore 创建一个新行,并且您有 4 个(每个 user/subject 1 个,所以您最终当然有 4 行)。

你的 tbody 应该是这样的:

<tbody>
  <% @students.each do |student| %>
    <tr>
      <td><%= student.name %></td>
      <% @subjects_by_class.each do |subject| %>
        <% @examscore.each do |score| %>
          <% if score.subject_id == subject.id && score.student_id == student.id %>
            <td><%= score.total %></td>
            <% break %>
          <% end %>
        <% end %>
      <% end %>
      <td><%= sum_student_totalscore(student.id, year_id) %> </td>
      <td><%= avg_student_totalscore(student.id, year_id) %></td>
    </tr>
  <% end %>
</tbody>

有点奇怪,你的总数只关心年份

你也可以通过在你的 Student class 中使用一个方法来改进一些事情 returns 给定 year/list 科目

的一组分数
# Returns an array of scores for the given year
def scores(year, subject_ids)
  subject_ids.map do |subject_id|
    # find score for year & the given subject_id
  end
end

这样你的body就会变成

<tbody>
  <% @students.each do |student| %>
    <tr>
      <td><%= student.name %></td>
      <% @scores = student.scores(year_id, @subjects_by_class) %>
      <% @scores.each do |score| %>
        <td><%= score.total %></td>
      <% end %>
      <% scores_total = @scores.sum(&:total) %>
      <td><%= scores_total %> </td>
      <td><%= scores_total / @scores.size.to_f %></td>
    </tr>
  <% end %>
</tbody>

我发现它更清楚,但它可以通过装饰器等进一步改进。