How would I val开发者_StackOverflowidate a field only if another has been filled out In Ruby on Rails 2.3.5?
class Model < ActiveRecord::Base
validates_presence_of :address, :if => :city?
end
:address
and :city
are both attributes of Model
.
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? }
精彩评论