2016-05-21 25 views
1

我有兩個數組,我想創建一個動態標題單元格(來自第一個數組,名爲subjects)並反覆添加內容(來自第二個數組稱爲examscores)在表格行中相對於表頭值。如何創建一個非靜態的HTML表格標題和行

期望的結果是(fiddle):

enter image description here

該局代碼:

<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):

enter image description here

Maths主題下創建新的tr,而不是Arts主題的新td主題,並且導致Averagetd失真。

任何有識之士將不勝感激。

回答

0

那麼,就看看你的代碼的這一部分:

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

您創建的每個@examscore一個新行,你有這些的4(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> 

這是一個有點奇怪,你只能在你的總數關心的一年有一個方法

你也可以改善的東西一點點你的學生類返回分數的數組的對象

# 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 

這樣一個特定年份/列表你的身體會變得

<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> 

其中我發現更清楚,但它可以進一步改善與裝飾器例如。