4

I have a basic ActiveRecord model in which i have two fields that i would like to validate. The requirement is that at least one of the fields must have a value. Both can have values, but at least one needs a value.

How do i express this with

validates_presence_of 

statements? For example:

validates_presence_of :main_file
validates_presence_of :alt_file

i don't want an error to be generated if only one of them is empty, only if both are empty.

2 Answers 2

5
validates_presence_of :main_file, :if => Proc.new { |p| p.alt_file.blank? }
validates_presence_of :alt_file, :if => Proc.new { |p| p.main_file.blank? }
Sign up to request clarification or add additional context in comments.

1 Comment

Wouldn't it be better to blank? instead of nil??
3

changing .nil? to .blank? does the trick!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.