views:

43

answers:

2

How would I validate a field only if another has been filled out In Ruby on Rails 2.3.5?

+1  A: 
class Model < ActiveRecord::Base

  validates_presence_of :address, :if => :city?

end

:address and :city are both attributes of Model.

Simone Carletti
That works! Thank you. I ended up needing to specify a proc. See my answer for the three different things the `if` attribute accepts.
yuval
+2  A: 

validates_presence_of accepts an if attribute that take one of three things, according to the documentation: a string, a method, or a proc.

if - Specifies a method, proc or string to call to determine if the validation
should occur (e.g. :if => :allow_validation, or
:if => Proc.new { |user| user.signup_step > 2 }).
The method, proc or string should return or evaluate to a true or false value.

I ended up needing to use a proc, as I wanted to make sure that a certain parameter was filled out before validating:

  validates_presence_of :bar, :if => Proc.new { |foo| !foo.age.blank? }
yuval
Instead of creating and answer, I suggest to edit your original question.
Simone Carletti