Use of Conditional (IF) in Model Validations
By: Bruce Bahlmann - Contributing Author (your
is important to us!)
In rails development, when creating web forms, you often have a particular
field dependent on another. For example, lets say you have a checkbox (boolean)
input value whose value controls the need for an additional text input
value. As such, when adding validation to to these fields within the model,
you must either make these fields optional, or if you want to make them
dependent on the setting of this checkbox (used in this particular example)
you need to use a conditional.
Fortunately, Ruby on Rails (RoR)
provides an easy way to validate these without creating a "custom
validation" (which is an alternative way to do this, albeit more
complicated). Simply place the [:if] after the validates entry for the field
which is dependent on another input field.
Class Post < ActiveRecord::Base
Validates :<field name>, :presence => true, :if => "<field checked> == true"
The above entry with in app/models/post.rb reads as follows. Validates
would require the presence of a value within the <field name> (name of the
text input field) IF the <field check> (the name of the checkbox input
field) was set to true.
Note: a checkbox field is not "nil", rather it is either true if
checked, or false if either not checked or not set.
|Can Birds-Eye.Net help you or your Company?
Receive your Birds-Eye.Net articles and white
papers hot off
the presses by adding our RSS feed to your reader.
(C) Copyright Birds-Eye.Net, All rights reserved.
It is against the law to reproduce this content or any portion of it in any form without the explicit written permission of Birds-Eye Network Services, LLC. Federal copyright law (17 USC 504) makes it illegal, punishable with fines up to $100,000 per violation plus attorney's fees.