SameShirtEveryDay.com

Personal blog of the one called Alex Gorbatchev, from Toronto, Canada.

Validating presence of a boolean field

Posted on May 13th, 2007 by Alex Gorbatchev. In Rails.

A little gotcha about validating presence of boolean fields from the doc:

If you want to validate the presence of a boolean field (where the real values are true and false), you will want to use validates_inclusion_of :field_name, :in => [true, false] This is due to the way Object#blank? handles boolean values. false.blank? # => true.

I personally find this a bit misleading. To me validate_presence_of implies that a check to see if there’s a value assigned. As far as I know nil is used to indicate the lack of such value. Furthermore, false.blank? is true which I think is wrong because false is a value.

The whole meaning of blank? seem to start loosing its value when you consider that nil.blank? == [].blank? == {}.blank? == “”.blank? == false.blank? == true. I think there’s a much better way to handle a check for emptiness, or rather a default value of something. I’m also a strong believer that nil.anything should raise an exception… but that’s just my C roots talking.

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

One comments so far...

  1. David

    Thanks for the entry. I just hit my head against a wall for half an hour trying to understand why the hell this was happening

Leave a Reply

Allowed tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> , rel="nofollow" in use - no link dropping, no keywords or domains as names; do not spam, and do not advertise!

home
Subscribe to this blog Follow me on Twitter My bookmarks on Delicious My photography on Flickr