我必须在用户输入货件详细信息后在结帐页面上显示总价。我的购物车模型有一个total_price方法,我在视图上使用它来显示总价格,如
<%= number_to_currency(@cart.total_price) %>
现在我想显示总计为total_price +货运的总额。使用三个参数重量,状态和提供商计算出货量。假设现在州和提供商不变,我们只需要担心权重。所以为此,我在购物车模型中有一个shipping_rate方法,类似于。
def shipment_rate(weight, provider, state)
# calculation code here
end
在这样的视图中使用此方法是否合适:
<%- shipment = cart.shipment_rate(weight,'UPS','AK')%>
为此,我必须提供购物车物品的总重量,我可以使用方法@ cart.total_weight计算。 Rails的做法是什么?从View中调用这些方法是否合适如下:
<%- total = @cart.total_price %>
<%- weight = @cart.total_weight %>
<%- shipment = cart.shipment_rate(weight,'UPS','AK')%>
...
然后在同一个视图中使用以下这些值,如
<span>Amount: <%= number_to_currency total %></span>
<span>Shipment: <%= number_to_currency shipment %></span>
<span>Total: <%= number_to_currency total + shipment %></span>
答案 0 :(得分:1)
我会把它全部放回模型中:
<span>Amount: <%= number_to_currency @cart.subtotal %></span>
<span>Shipment: <%= number_to_currency @cart.shipping %></span>
<span>Total: <%= number_to_currency @cart.total %></span>
小计是你现在所说的“total_price”,“total”是小计+运费
毕竟 - 购物车已经知道自己的重量以及如何从中计算出货率 - 因此您需要询问的是出货率。 如果需要,可以将值传递给它:
<span>Amount: <%= number_to_currency @cart.subtotal %></span>
<span>Shipment: <%= number_to_currency @cart.shipping(provider,state) %></span>
<span>Total: <%= number_to_currency @cart.total(provider,state) %></span>