How to check a field only if another is filled?

How can I check a field only if the other was populated in Ruby on Rails 2.3.5?

+4
source share
2 answers
class Model < ActiveRecord::Base validates_presence_of :address, :if => :city? end 

:address and :city are attributes of the Model .

+7
source

validates_presence_of accepts an if attribute, which takes one of three things according to the documentation : string, method, or use.

 if - Specifies a method, proc or string to call to determine if the validation should occur (eg :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 had to use proc, because I wanted to make sure that a certain parameter was filled before the check:

  validates_presence_of :bar, :if => Proc.new { |foo| !foo.age.blank? } 
+5
source

Source: https://habr.com/ru/post/1302554/


All Articles