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
2010-02-27 00:46:14
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
2010-02-27 07:24:18
+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
2010-02-27 07:23:02
Instead of creating and answer, I suggest to edit your original question.
Simone Carletti
2010-02-27 10:48:14