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