簡體   English   中英

在Rails中以Rails方式顯示購物車總數

[英]Displaying cart total in Rails, the Rails way

用戶輸入貨運明細后,我必須在結帳頁面上顯示總價。 我的購物車模型有一個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> 

我將其全部放回模型中,如下所示:

<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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM