2012-08-05 28 views
0

我有一个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)。

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模型试过这种验证价格与所有领域填补。什么需要解决?

回答

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上的最后一个条件的错字!?

我希望帮助。

+0

感谢抓我错字,这是'blank'不是在unit_quantity结束。 – LearningRoR 2012-08-06 01:33:07

+0

一点问题都没有! – Tabrez 2012-08-06 09:21:56