我有一个Price
具有 4 个不同字段的模型:
t.decimal "amount"
t.decimal "amount_per_unit"
t.decimal "unit_quantity"
t.string "unit"
我正在尝试进行自定义验证,以允许填充amount
oramount_per_unit
字段(包括unit quantity
and unit
)但不能同时填充它们。所以做一个字图来表达我的意思。
amount = YES
amount_per_unit + unit + unit_quantity = YES
amount_per_unit (alone or amount.present) = NO
unit_quantity (alone or amount.present) = NO
unit (alone or amount.present) = NO
amount and amount_per_unit + unit + unit_quantity = NO
如果您仍然感到困惑,请知道它要么是填写的金额本身,要么是(1 或 3)的单位金额字段。
到目前为止,我在我的Price
模型中尝试了这个验证:
validates :amount, :numericality => true
validates :amount_per_unit, :numericality => true
validates :unit_quantity, :numericality => true
validates :unit, :inclusion => UNITS
validate :must_be_base_cost_or_cost_per_unit
private
def must_be_base_cost_or_cost_per_unit
if self.amount.blank? and self.amount_per_unit.blank? and self.unit.blank? and self.unit_quantity
# one at least must be filled in, add a custom error message
errors.add(:amount, "The product must have a base price or a cost per unit.")
return false
elsif !self.amount.blank? and !self.amount_per_unit.blank? and !self.unit.blank? and !self.unit_quantity
# both can't be filled in, add custom error message
errors.add(:amount, "Cannot have both a base price and a cost per unit.")
return false
else
return true
end
end
此验证不起作用,因为所有字段都是空白的,它会导致numericality
错误,如果我填写所有字段,它会创建填充所有字段的价格。需要修复什么?