2012-04-09 16 views
12

ここで私は完全に直接的な質問であることを期待していますが、ガイドやその他のところで決定的な答えを見つけることはできません。Rails 3検証:存在=>偽

私はActiveRecordに2つの属性を持っています。私はちょうど1つが存在し、もう1つはゼロまたは空の文字列にしたい。

これに相当するのはどうすればいいですか?存在=>偽ですか?私は値がゼロであることを確認したい。

validates :first_attribute, :presence => true, :if => "second_attribute.blank?" 
validates :second_attribute, :presence => true, :if => "first_attribute.blank?" 
# The two lines below fail because 'false' is an invalid option 
validates :first_attribute, :presence => false, :if => "!second_attribute.blank?" 
validates :second_attribute, :presence => false, :if => "!first_attribute.blank?" 

それとも、これを行うにはよりエレガントな方法があります...

私はRailsのを実行している3.0.9

+0

私はあなたが必要とするかわからない:プレゼンスを=>偽のすべてのコードの最後の2行で。 – creativetechnologist

+0

@creativetechnologist何らかのテストが必要です。存在確認を取り除くと、C:/Ruby192/lib/ruby/gems/1.9.1/gems/activemodel-3になります。 0.9/lib/active_model/validations/validates.rb:79: 'validates ':少なくとも1つのバリデーション(ArgumentError)を提供する必要があります。 – LikeMaBell

+6

Rails 4に注目する価値があります。これは' validates_absence_of'です。 – mpowered

答えて

8
class NoPresenceValidator < ActiveModel::EachValidator                                       
    def validate_each(record, attribute, value)         
    record.errors[attribute] << (options[:message] || 'must be blank') unless record.send(attribute).blank? 
    end                   
end  

validates :first_attribute, :presence => true, :if => "second_attribute.blank?" 
validates :second_attribute, :presence => true, :if => "first_attribute.blank?" 

validates :first_attribute, :no_presence => true, :if => "!second_attribute.blank?" 
validates :second_attribute, :no_presence => true, :if => "!first_attribute.blank?" 
0

試してみてください。助け

validates :first_attribute, :presence => {:if => second_attribute.blank?} 
validates :second_attribute, :presence => {:if => (first_attribute.blank? && second_attribute.blank?)} 

希望。

1

次のようになります。length => {:is => 0}は私が必要とするもののために機能します。

validates :first_attribute, :length => {:is => 0 }, :unless => "second_attribute.blank?" 
+1

これは、「間違った長さです(0文字にする必要があります)」というエラーメッセージが表示されます。カスタムメッセージ「空白でなければならない」を追加できます。 => "=" "second_attribute.blank?"のように、空白でなければなりません。 – tfentonz

3

カスタム検証を使用します。そして特定の属性がnilである場合にのみ、あなたではなく、独自のメソッドを作成するよりも、「インクルージョン」を使用することができた場合にオブジェクトが有効であることを可能にするための

23

validate :validate_method 

# validate if which one required other should be blank 
def validate_method 
    errors.add(:field, :blank) if condition 
end 

validates :name, inclusion: { in: [nil] } 

これは、4ソリューションは、Railsの3 Railsのためにはるかにエレガントされている。

validates :name, absence: true 
関連する問題