2013-09-30 55 views
0

我必須在用戶輸入貨件詳細信息後在結賬頁面上顯示總價。我的購物車模型,我用在視圖中顯示的總價類似在Rails中顯示購物車總額,Rails方式

<%= number_to_currency(@cart.total_price) %> 

現在我想顯示總計是TOTAL_PRICE +裝運TOTAL_PRICE方法。裝運使用三個參數重量,狀態提供者計算。假設狀態爲供應商是恆定的,現在我們只需要擔心重量。所以爲此,我在購物車模型中有一個shipment_rate方法。

def shipment_rate(weight, provider, state) 
     # calculation code here 
    end 

這是好到這樣的視圖中使用這個方法:

<%- shipment = cart.shipment_rate(weight,'UPS','AK')%> 

爲此,我必須提供車中的物品的總重量,以及我可以計算出使用方法@ cart.total_weight。 Rails的做法是什麼?這是好來調用查看這些方法如下:

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

只是出於好奇:你爲什麼不使用[施普雷商務部(http://spreecommerce.com) 如果需要例如可以將值傳遞到它? –

+0

@RyanBigg我打算使用[active_shipping](https://github.com/Shopify/active_shipping),但客戶端有一些自定義實現記在 – androidharry

+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」 和 「總」 是大部+運費

畢竟 - 購物車已經知道它自己的重量以及如何從中計算出貨率 - 因此,您只需要詢問它就是發貨率。

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

謝謝,這聽起來不錯,但我還有一個問題。在@ cart.total方法中,我們將再次調用** shipping **方法,因爲該值不存儲在某處。 – androidharry

+1

是的。如果它不是一個非常複雜的等式 - 它將對您的響應時間產生近乎微不足道的影響,並且通過在模型中將其忽略掉而節省的認知負荷(加上在模型測試中完全測試的能力)超過了倍增的小影響。 如果它是一個複雜的等式,那麼我建議你谷歌「memoization」 - 它只是將值存儲在實際*實例*上的臨時變量中,因此不會重新運行邏輯。只需重新獲取價值。但說實話,除非這是一個調用遠程服務器的調用,否則它可能不值得。 :) –

+0

在會話中存儲這些值是一個很好的選擇嗎? – androidharry