Validations on empty (not nil) attributes
One of the first problems that I ran into when I started using Rails was trying to validate the format of attributes that aren’t required. Most of the validations have an :allow\_nil
option, but the problem is that when a form is submitted with empty form fields, those fields are empty strings instead of nil values. So the validation fails because the attribute is not nil.
For example, here’s a Person model with a validation on :social\_security\_number
, an optional attribute:
When this model is used in a form, validation will fail if the social security number field is left blank, even though :allow\_nil
is set to true.
The solution
It turns out that the solution is really simple: a before\_validation
callback that just goes through and sets all the empty attributes to nil.
I’ve packaged this little nugget into a plugin. Install it and go on your merry validating way.
script/plugin install -x git://github.com/collectiveidea/clear_empty_attributes.git