验证不允许使用两个字段问题

时间:2012-08-05 22:41:30

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1

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

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

我尝试进行自定义验证,允许填充amountamount_per_unit字段(包括unit quantityunit),但不能他们都。所以要制作一个我的意思的字图。

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错误,如果我填写所有字段,则会创建所有字段填写的价格。需要修复什么?

1 个答案:

答案 0 :(得分: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?

我希望有所帮助。