Rails将两个值相加在一起

时间:2014-01-30 16:11:50

标签: ruby-on-rails

我的expenses列有:quantityunitcost。总费用金额为:quantity * unit cost

woassets have_many :expenses

我想显示asset索引列表中每个asset的总计。

这有效:

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

但是,有更好的方法吗?

我尝试在expense total模型中定义expense,如下所示:

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

然后在索引中:

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

但是,这没效果。

感谢您的帮助

1 个答案:

答案 0 :(得分: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 %>