2017-06-02 23 views
0

我試圖爲目錄中的每個單獨產品實現折扣。 我添加了新的字段到產品表 - 折扣。 如果discount.present如何重新計算product.price?如何在rails中實現產品折扣

我嘗試添加幫手product.rb:

def price 
old_price = self.price 
if self.discount.present? 
    self.price -= self.price/self.discount 
else 
    old_price 
end 

但它可以讓我「堆棧級別太深」錯誤

+0

「堆棧級別太深」幾乎總是意味着你有一個無限遞歸問題。一個函數調用自己沒有停止條件。 –

回答

4

你得到這個錯誤,因爲price不斷引用本身。通過創建一種顯示價格的新方法,您會變得更好。

def price_with_discount 
    return self.price if self.discount.nil? || self.discount.zero? 
    self.price - (self.price/self.discount) 
end 

然後你使用,在你看來

<%= product.price_with_discount %> 
+0

謝謝!但是如果我需要同時顯示新舊價格呢? – alexxero

+1

然後只顯示價格,'<%= product.price%>' – Iceman

+1

這是關於分離兩者的好處,因此您可以顯示您想要的任何一個。 – Iceman

相關問題