ruby-on-rails-3 – rails计算小计和总计的方法
发布时间:2020-12-17 02:42:24 所属栏目:百科 来源:网络整理
导读:上下文:我有2个模型Order和Item. 我想根据item.quantity * item.price计算Item小计 目前,这是在视图中完成的(但不是适当的地方). %= number_to_currency(item.quantity * item.price) % 我还需要计算订单总数但我被卡住了.我没有任何专栏. 什么是最好的方法
上下文:我有2个模型Order和Item.
我想根据item.quantity * item.price计算Item小计 <%= number_to_currency(item.quantity * item.price) %> 我还需要计算订单总数但我被卡住了.我没有任何专栏. 现在我设法通过Order helper进行小计工作 def item_subtotal(item) item_subtotal = item.quantity * item.price end 工作方案: 物品模型 def subtotal price * quantity end 在视图渲染<%= item.subtotal%> 订单模型 def total_price total_price = items.inject(0) { |sum,p| sum + p.subtotal } end 订单#show view render<%= number_to_currency(@ order.total_price)%> 解决方法
在Item模型上,您可以添加小计方法:
def subtotal quantity * price end 假设您将Order模型作为与Item的has_many关系,您可以映射集合以获取Order模型上的价格列表: def subtotals items.map do |i| i.subtotal end end 因为您在Rails环境中运行,所以可以使用activesupport sum方法获取Order模型的总计: def total subtotals.sum end 或者如果你喜欢把它们放在一起: def total items.map do |i| i.subtotal end.sum end 然后,您可以在视图中使用Item上的小计和Order上的Total. 编辑:视图可能如下所示: <% for item in @order.items %> <%= item.price %><br/><% end %> <%= @order.total %> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |