4つの異なるフィールドを持つPrice
モデルがあります。
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)のいずれかであることを知っておいてください。
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
エラーが発生し、すべてのフィールドに入力すると、すべてのフィールドに入力された価格が作成されます。何を修正する必要がありますか?