Validating Booleans

I came across a little gotcha today and thought it would be nice to start a series of ‘One Minute Rails’ posts. The idea is they’re super short, practical posts that you can digest within a minute and gain a practical piece of knowledge or insight that you can take away and apply to whatever you’re working on.

I was working on an application today where the Users model called for an admin boolean and I wanted to make this a required field for all users, so I stuck on the standard…

…and my test were still failing even though I knew admin was now a required field, or so I thought.

To understand why presence: true doesn’t work for boolean fields, we have to take a peak at how Rails is validating these fields. Rails’ way of validating presence is to use .blank? to check if something is blank, but if you try this on a false value ( false.blank? ) it returns true, confirming that the field is blank and failing validation miserably. The trick is to check that the boolean field is either one of an array of specified values. We can do this using inclusion like so…

A simple trick that will save you some serious frustration on those boolean validations.




Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">