0
我有一个Price
模型4个不同的领域:验证不允许这两个领域使用问题
t.decimal "amount"
t.decimal "amount_per_unit"
t.decimal "unit_quantity"
t.string "unit"
我试图做一个自定义的验证,让无论是amount
或amount_per_unit
领域(包括unit quantity
和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)。
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
错误,如果我填的所有的人,它会创建工作:
到目前为止,我在Price
模型试过这种验证价格与所有领域填补。什么需要解决?
感谢抓我错字,这是'blank'不是在unit_quantity结束。 – LearningRoR 2012-08-06 01:33:07
一点问题都没有! – Tabrez 2012-08-06 09:21:56