Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying two conditions with :if

I have a model which validates presence of an attribute if a check box is checked in the view.

The code is something like this:

validates_presence_of :shipping_first_name, :if => :receive_by_email_is_unchecked

I am looking to have another condition of this validation.So how do I go about doing this ??

My assumption is that something like this would do:

validates_presence_of :shipping_first_name, :if => {:receive_by_email_is_unchecked,:form_first_step_validation}

I am not sure if this is the write way of doing it or not ??

Any suggestions would be appreciated.

like image 447
Smoke Avatar asked Feb 22 '26 10:02

Smoke


1 Answers

You can pass method names in an array:

validates_presence_of :shipping_first_name, :if => [:receive_by_email_is_unchecked, :form_first_step_validation]

Alternatively you can use proc if you don't want to define separate methods just for conditioning validations:

validates_presence_of :shipping_first_name, :if => proc { !receive_by_email? && form_first_step_validation }
like image 178
Michał Szajbe Avatar answered Feb 25 '26 03:02

Michał Szajbe