0

我有一个CommercialDocument具有discount_amount属性和discount_amount_with_tax虚拟属性的模型。

这是我在模型中定义的方式:

def discount_amount_with_tax
  discount_amount * (1 + tax.rate / 100)
end

def discount_amount_with_tax=(amount)
  self.discount_amount = amount.to_f / (1 + tax.rate / 100)
end

在我的表格中,用户可以同时填写discount_amountdiscount_amount_tax

= f.label :discount_amount
= f.text_field :discount_amount
= f.text_field :discount_amount_with_tax

我想优先考虑该discount_amount_with_tax字段,这意味着discount_amount除非其他字段为空,否则不得考虑。

我的问题是,如果我什么都不放在discount_amount_with_tax字段中,比如说 10 in discount_amount,那么discount_amount将等于 0,这显然不是我想要的。

我怎样才能解决这个问题 ?

任何帮助将不胜感激。

4

2 回答 2

1
"".to_i
# => 0

空白字符串转换为零整数。所以:

def discount_amount_with_tax=(amount)
  self.discount_amount = amount.to_f / (1 + tax.rate / 100)
end

# same as...

def discount_amount_with_tax=(0)
  self.discount_amount = 0 / (...)
end

# 0 / anything except zero = 0
# self.discount_amount = 0 no matter what

在批量分配期间,discount_amount_with_tax=被调用。空白表单输入作为空字符串传递,然后 Active Record 将其转换为整数(零)。无论' 的先前值如何,都discount_amount_with_tax=设置为零。discount_amountdiscount_amount

解决此问题的简单方法是使用条件:

def discount_amount_with_tax=(amount)
  self.discount_amount = (amount.to_f / (1 + tax.rate / 100)) if amount > 0
end

请注意,这是简单的方法,而不是理想的方法。更好的解决方案是在控制器中编写自定义设置器逻辑来代替批量赋值;基本上是在控制器中手动设置这些属性。

于 2013-01-30T09:29:11.463 回答
0

我认为您可以在此处使用 before_validation 回调来设置 discount_amount 字段。

  before_validation :calculate_discount_amount

  def discount_amount_with_tax
    @discount_amount_with_tax ||= discount_amount * (1 + tax.rate / 100.0)
  end

  def discount_amount_with_tax=(amt)
    @discount_amount_with_tax = amt
  end

  def calculate_discount_amount
    self.discount_amount = discount_amount_with_tax / (1 + tax.rate / 100.0)
  end

只是提醒您,您需要使用 100.0 而不是 100,以便您将除以浮点数而不是整数。

于 2013-01-30T09:29:28.583 回答