我创造了一个小工具,可以根据售出的价格从另一张桌子中扣除价格。这完全没问题。 但是我需要在其中加入折扣逻辑。应该有3种方式给予折扣:
以上所有内容也可以免除一次性安装费(SuF)。
不幸的是,折扣逻辑不起作用,我无法找到原因。所有东西(价格,安装费等)都正确添加到记录中,但不是折扣。此外, discountquantity,discount_percentage,waive_suf 的值也会保存到记录中。因此,输入相应if条款的条件应该在那里。我在这里缺少什么?我的猜测是我没有正确地返回值来保存它。我没有错。 折扣的值不会保存到数据库中。
请在下面的代码中找到解释:
sale.rb
class Sale < ActiveRecord::Base
...
before_save :discount
...
def discount=(discount)
#checks if manually typed discount is present and the discount value is not greater than the value defined in the user model (maxdiscount)
if discount.present? && current_user.maxdiscount >= discount.to_d
discount.to_s.gsub(",", ".") #need to transform comma into point
discount = discount.to_d * quantity
discount
end
#checks if discountquantity (1,2,3 months for free) is present
if discountquantity.present? #discountquantity is the value (1,2,3) months for free
discount = discountquantity * price
discount
end
#checks if discount is 10%
if discount_percentage = 10 #discount_percentage can be selected from the user in a dropdown
discount = price * quantity * 0.90
discount
end
#checks if discount is 25%
if discount_percentage = 25
discount = price * quantity * 0.75
discount
end
#checks if SuF should be waived
if waive_suf == true #can be selected from the user
#if available the Setup fee gets pulled from another table
if Warehouse.where(:product => self.product).where(:brand => self.order.brand).pluck(:suf).present?
suf = Warehouse.where(:product => self.product).where(:brand => self.order.brand).pluck(:suf).sum
suf = suf.to_d * quantity
suf
end
if setup.present? #can be entered manually
setup = setup.gsub(",", ".")
setup = setup.to_d * quantity
setup
end
setup_fee = suf + setup #sums that up
end
self[:discount] = discount + setup_fee
end #def discount=(discount)
end
销售模式(简化)
t.integer "quantity", default: 1
t.text "comment"
t.decimal "discount"
t.decimal "price"
t.decimal "setup"
t.integer "discountquantity"
t.boolean "waive_suf", default: false
t.integer "discount_percentage"
许多人提前感谢!
答案 0 :(得分:0)
您为什么要def discount=(discount)
,然后执行before_save :discount
,def discount=(discount)
将在Sale.new(discount: 'something')
时运行,请尝试更改为def discount
。
class Sale < ActiveRecord::Base
before_save :discount
def discount
end
end
同样只是一个代码审查提示,这个方法非常长,并且在if条件下有很多分支,将其减少到多个方法。