2017-03-16 17 views
1

の追加、条件付きカスタム検証がレール5:私はモデルに条件付きのカスタム検証を追加したい

Railsはまた、条件を作成することができます

class Invoice < ApplicationRecord 
    validate :expiration_date_cannot_be_in_the_past 

    def expiration_date_cannot_be_in_the_past 
    if expiration_date.present? && expiration_date < Date.today 
     errors.add(:expiration_date, "can't be in the past") 
    end 
end 

をカスタム検証を作成するためのメソッドを作成することができます検証

class Order < ApplicationRecord 
    validates :card_number, presence: true, if: :paid_with_card? 

    def paid_with_card? 
    payment_type == "card" 
    end 
end 

は、どのように私は両方を混在させることができますか?

私の推測では、

validate :condition, if: :other_condition 

ようなものになるだろう。しかし、これはにSyntaxErrorを作成します。

syntax error, unexpected end-of-input, expecting keyword_end 

答えて

3

あなたが不足している決算を修正する場合endexpiration_date_cannot_be_in_the_pastに開設すると、動作:

validate :expiration_date_cannot_be_in_the_past, if: :paid_with_card? 
2

あなたは終わりを逃し、コードを修正:

class Invoice < ApplicationRecord 
    validate :expiration_date_cannot_be_in_the_past 

    def expiration_date_cannot_be_in_the_past 
    if expiration_date.present? && expiration_date < Date.today 
     errors.add(:expiration_date, "can't be in the past") 
    end # this end you missed in code 
    end 
end 
2

各バリデータは使用できます。このためには、次の手順に従っする必要があります。

  • はあなたappディレクトリ内validatorsという名前のフォルダを作成します。
  • などsome_validator.rb
  • 書き込みコードをという名前のファイルを作成します。 validates :attribute_name, some: true

  • ご確認してください:

    class SomeValidator < ActiveModel::EachValidator 
    def validate_each(object, attribute, value) 
        return unless value.present? 
        if some_condition1 
        object.errors[attribute] << 'error msg for condition1' 
        end 
        object.errors[attribute] << 'error msg 2' if condition2 
        object.errors[attribute] << 'error msg 3' if condition3 
        object.errors[attribute] << 'error msg 4' if condition4 
    end 
    

    エンド

  • 今すぐなど、このカスタムバリデータによる検証をバリデーターで同じ名前を与えています。このカスタムバリデーター内に複数の条件を記述することができます。

関連する問題