我的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_amount
和discount_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
字段中没有放任何内容,让我们在discount_amount
中说10,那么discount_amount
将等于0,这显然不是我想要的
我该如何解决这个问题?
非常感谢任何帮助。
答案 0 :(得分: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_amount
都会将discount_amount
设置为零。
简单来说就是使用条件:
def discount_amount_with_tax=(amount)
self.discount_amount = (amount.to_f / (1 + tax.rate / 100)) if amount > 0
end
请注意,这是简单方法,而非理想方式。更好的解决方案是在控制器中编写自定义设置器逻辑,而不是质量分配;基本上手动在控制器中设置这些属性。
答案 1 :(得分: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,这样你就可以用浮点而不是整数来划分。