2014-01-30 68 views
0

我有expenses有列::quantityunitcost。總費用金額爲:quantity * unit costRails總和兩個值相乘

woassetshave_many :expenses

我想在asset索引列表中顯示每個asset的總數。

這工作:

<% expensetotal = 0 %> 
    <% woasset.expenses.each do |expense| %> 
     <% expensetotal = expensetotal + (expense.quantity.to_i * expense.unitcost) %> 
    <% end %> 
    <td><%= expensetotal %></td> 

但是,有沒有更好的辦法?

我試圖在expense模型定義expense total,像這樣:

def expense_amount 
"#{self.quantity} #{self.unit_price}" 
end 

那麼這個索引:

<%= woasset.expenses.sum(:expense_amount) 

但是,沒有工作。

感謝您的幫助

+1

會是什麼意思總結包含兩個數字的字符串?無論如何,爲什麼不在創建/更新/保存/其他方面填寫費用總額? –

+0

您也可以使用聚合函數直接在數據庫中執行此操作。你應該研究一下,因爲一般來說,讓數據庫工作然後返回答案比獲取數據然後在服務器上完成工作要快。 – MrDanA

+0

這些都是很好的選擇 - 謝謝 – Reddirt

回答

0

這應該工作

<td><%= woasset.expenses.map{|e| e.quantity * e.unitcost}.reduce(:+) %></td> 

。當然,這是更好地解壓到一個模型

class Woasset 
    def total_expense 
    expenses.map{|e| e.quantity * e.unitcost}.reduce(:+) 
    end 
end 

<%= woasset.total_expense %> 
+0

感謝您的幫助! – Reddirt