嗨,我有一個表,我列出不同的值。現在我想將一個總值添加到我的表中,該值對每列的值進行計數並將其添加到具有總值的列中。我該怎麼做呢?是否有可能在視圖中以一種簡單的方式做到這一點,還是我一定會在模型中做到這一點?謝謝你的幫助!如何從表格列添加值?
<div class="chart-data">
<table>
<caption>Data</caption>
<thead>
<tr>
<% statistic.column_titles.each do |column| %>
<th><%= column %></th>
<% end %>
<th>Total</th>
</tr>
</thead>
<tbody>
<% statistic.rows.each do |row| %>
<tr>
<th scope="row"><%= row.title %></th>
<% row.data.each do |column| %>
<td><%= column %></td>
<% end %>
</tr>
<------- Here i want to have the code that sums the values from the columns above to form the 'Total'
<% end %>
</tbody>
</table>
</div>
在執行此操作的範圍中遇到問題。我試過<%row.data.each do | column |%><%= total = total + column%> <%= total %> <% end %>但即時獲取總數爲零。也許是某種範圍問題 – 2010-11-15 10:01:40
你是否在循環之外初始化總數爲0?你可以試試row.data.inject(:+)[ruby> 1.8.7]或row.data.inject(0){| s,n | s + = n} [ruby> = 1.8.6,雖然不太優雅,但速度更快] – Jakobinsky 2010-11-15 10:25:15
不,我不初始化它。我應該這樣做嗎? – 2010-11-15 10:30:35