2010-11-15 51 views
0

嗨,我有一個表,我列出不同的值。現在我想將一個總值添加到我的表中,該值對每列的值進行計數並將其添加到具有總值的列中。我該怎麼做呢?是否有可能在視圖中以一種簡單的方式做到這一點,還是我一定會在模型中做到這一點?謝謝你的幫助!如何從表格列添加值?

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

回答

2

簡單的解決方案是維護一個總結列的變量,然後在最後使用它。

+0

在執行此操作的範圍中遇到問題。我試過<%row.data.each do | column |%><%= total = total + column%> ​​<%= total %> <% end %>但即時獲取總數爲零。也許是某種範圍問題 – 2010-11-15 10:01:40

+1

你是否在循環之外初始化總數爲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

+0

不,我不初始化它。我應該這樣做嗎? – 2010-11-15 10:30:35

2
class Row < ActiveRecord::Base 
    def total_spent 
    sum(:data) 
    end 
end 

<tbody>  
    <% @rows.each do |row| %> 
    <tr> 
     <th scope="row"><%= row.title %></th> 
     <% row.data.each do |column| %> 
     <td><%= column %></td> 
     <% end %> 
    </tr> 
    <td><% row.total_spent %></td> 
    <% end %> 
</tbody> 

假設當然這行是一個模型,你可以在行模型中移動這個邏輯。如果你喜歡,你也可以緩存頁面。

+0

感謝您的回答。我將邏輯移至Row模型,但在視圖中無法正確實施。你寫@ rows.each,這是否有所作爲?現在,我必須使用statistic.rows或者根本不顯示任何表格。當我使用statistic.rows,模型中的邏輯和出於某種原因row.total_spent時,根本沒有表格顯示。它可能是範圍問題嗎?我想這應該是使用@rows的原因,但由於某種原因它不起作用。嗯。 – 2010-11-15 10:29:27

+0

在統計控制器#索引[或任何此表是]添加:'@rows = Row.all' – Jakobinsky 2010-11-15 10:47:05

0

如果您的數據是針對數據庫的ActiveRecord查詢的結果,則可以要求數據庫執行彙總所有列的工作。這將是一個額外的查詢,但會很快運行,因爲這是數據庫設計的目的。