2011-10-25 85 views
1
<% for product in @order.line_items -%> 
<% total_price += (product.price * product.quantity) -%> 
<tr> 
    <td><strong><%= product.item.description%></strong></td> 
    <td><%= product.item.category.category_name%></td> 
    <td><%= product.quantity%></td> 
    <td><%= product.price%></td> 

</tr> 
<% end -%> 

如何将total_price保存到我的数据库?谢谢!将来自视图的数据保存到数据库中

回答

1

您应该添加一个方法,你Order模型计算的总价格的订单:

def total_price 
    line_items.sum('price * quantity') 
end 

用这个你可以做:

@order.total_price 

该方法的一个附加优点是计算在数据库中完成。无需迭代所有订单项。

2

在你的例子中,你正在视图中工作。该视图不是为了操纵其中的数据而显示数据。当你想补充一点,为您提供的总价格的方法,你可以把它添加到您的模型:

<%= product.total_price %> 

一个原则是:

def total_price 
    self.price*self.quantity 
end 

然后你就可以在你看来这样称呼它您从不将数据存储在数据库中,这些数据可以从数据库中已存在的其他字段中计算出来。

另外你也不应该使用for循环。使用迭代这样的:

<% @order.line_items.each do |product| %> 
     <%= stuff you do...... %> 
<% end %> 

当你想的和你可以这样做:

@order.line_items.collect(&:total_price).sum 
+0

谢谢!但我如何保留+ =功能? –

+1

'集合中的物品'只是写作'collection.each do | item |'的另一种方式。为什么*不应该*他使用那个? – Mischa

+0

没有工作。它说没有方法错误。 :( –