开发者

How to validate a field only if another has been filled out?

开发者 https://www.devze.com 2022-12-21 04:50 出处:网络
How would Ival开发者_StackOverflowidate a field only if another has been filled out In Ruby on Rails 2.3.5?class Model < ActiveRecord::Base

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? }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号