0

我有一个Price具有 4 个不同字段的模型:

t.decimal  "amount"
t.decimal  "amount_per_unit"
t.decimal  "unit_quantity"
t.string   "unit"

我正在尝试进行自定义验证,以允许填充amountoramount_per_unit 字段(包括unit quantityand 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错误,如果我填写所有字段,它会创建填充所有字段的价格。需要修复什么?

4

1 回答 1

1

我认为你的价值观是零,而不是空白。

尝试将第二个条件更改为:

elsif !self.amount.to_s.blank? and !self.amount_per_unit.to_s.blank? and !self.unit.to_s.blank? and !self.unit_quantity.to_s.blank?

此外,您似乎在两个语句的最后一个条件上都有错字(例如!self.unit_quantity 而不是 !self.unit_quantity.to_s.blank?

我希望这会有所帮助。

于 2012-08-05T23:41:20.990 回答