2014-10-07 24 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