2012-08-05 27 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