2014-10-07 46 views
0

我有一家小型的鐵路店,並且幫助者計算總價和折扣(如果已應用),但我想確定實際折扣顯示在視圖 -Rails,從2名傭工處獲得折扣金額

def total_price 
    price = 0 
    order_products.each do |order_products| 
     # add the item price to total 
     price += (order_products.price_in_pence * order_products.quantity) 
    end 
    apply_discount(price) 
    end 

    def apply_discount(price) 
    return price if discount.nil? 
    if discount.percentage.present? 
     price = price - ((price/100) * discount.percentage) 
    elsif discount.money.present? 
     price = price - discount.money 
    end 
    price < 0 ? 0 : price 
    end 

    def discount_amount 
    I need something here to take the total_price from above 
    before a discount and then the apply_discount and subtract the 2. 
    end 
+0

'discount_amount'不能像其他兩個助手一樣寫入。您需要解決'total_price'和'apply_discount',因爲當前正在調用另一個。你無法得到不同的值。 – meagar 2014-10-07 07:02:05

+0

您正在尋找物品/產品級別或訂單級別的折扣金額? – Surya 2014-10-07 07:10:31

+0

另外,儘量避免:'order_products.each do | order_products |'。改爲將管道中的變量更改爲不同。就像:'order_products.each do | order_product |',這樣你就不會與你在塊內執行的操作混淆。 – Surya 2014-10-07 07:11:59

回答

1

你應該重構折扣前的價格爲私有方法重用:

def total_price  
    apply_discount(price_before_discount) 
    end 

    def apply_discount(price) 
    return price if discount.nil? 
    if discount.percentage.present? 
     price = price - ((price/100) * discount.percentage) 
    elsif discount.money.present? 
     price = price - discount.money 
    end 
    price < 0 ? 0 : price 
    end 

    def discount_amount 
    price_before_discount - total_price 
    end 

    private 
    def price_before_discount 
     @price_before_discount ||= order_products.inject(0) do |sum, order_product| 
     # add the item price to total 
     sum += (order_product.price_in_pence * order_product.quantity) 
     end 
    end 
1

不知道你在哪裏從apply_discount越來越discount,但好像你要提供四個值在我看來:

  • 價格
  • 折扣率
  • 平折

所以,也許這樣的事情?

def price 
    order_productions.each { |p| p.price * p.quantity } 
end 

def percent_discount 
    1 - (discount.percentage || 0) # ie, 100% [or 0% off] when discount.percentage is nil 
end 

def flat_discount 
    discount.money || 0 # (ie, 0 dollars off) 
end 

def total 
    [(price * percent_discount) - flat_discount, 0].max # to ensure we get a positive value 
end 

(注:未經測試)

(您可能需要調整位的情況下,[如果是下]一個折扣既有百分比並在其上固定金額,或者如果折扣可以爲空)

+0

折扣是與has_many:訂單關聯的模型,感謝此。我會嘗試使用你的建議。折扣可以是%或貨幣價值,這就是爲什麼我在助手中有if語句的原因。有驗證只允許1。 – 2014-10-07 07:17:27

1

我將移動計算到discount_amount方法:

def total_price 
    order_products.inject(0) do |sum, product| 
    sum + (product.price_in_pence * product.quantity) 
    end 
end 

def discount_amount 
    return 0 unless discount 
    if discount.percentage.present? 
    (total_price/100) * discount.percentage 
    elsif discount.money.present? 
    discount.money 
    end 
end 

def total_price_after_discount 
    total_price - discount_amount 
end