0

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エラーが発生し、すべてのフィールドに入力すると、すべてのフィールドに入力された価格が作成されます。何を修正する必要がありますか?

4

1 に答える 1

1

あなたの値は空白ではなくゼロとして入ってくると思います。

2 番目の条件を次のように変更してみてください。

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.to_s.blank の代わりに!self.unit_quantity?

それが役立つことを願っています。

于 2012-08-05T23:41:20.990 に答える