Rails: Multiple validations on single condition

Came across this scenario, where we needed multiple validations to kick in on the same logical condition. It landed in repeating the condition for all the validation statements. But stumbled upon this option.

with_options :if => :email_notification_required? do |condition|

    condition.validates_presence of   :email_recipient_name

    condition.validates_length_of   :email_recipient_name, :maximum => 255, :allow_blank => true

    condition.validates_presence of   :email_address

    condition.validates_length of   :email_address, :maximum => 255


(The italicized fields are specific to the example. )

So all the validations in the block kick in only if the boolean method email_notification_required returns a true.

This may not always be the way to go, there may be indications that probably this is not the right place for all those validations, perhaps they can be moved out, but nonetheless, its an option you may need sometime.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s