Boolean portability under Rails

Posted on the November 3rd, 2008 under Computers by Martin Bergek

Booleans should be so simple. They can only have two values. As a former colleague used to say – How hard can it be? With all the variants of “0/1″, “Y/N”, “t/f” the answer seems to be – Apparently quite so.

Rails 2.0 switched the default database engine to sqlite3 and this has now caused me two issues. The first I wrote about some time back. The last one I just stumbled upon was related to booleans.

This works in MySQL:

@guests = Guest.find(:all, :conditions => 'accept = 1')

But it fails in sqlite3 since Rails stores booleans as ‘t’ or ‘f’ on that database engine. The portable way to write the condition in Rails is to make Rails itself select the proper value depending on the underlying database by writing it like this:

@guests = Guest.find(:all, :conditions => ['accept = ?', true])

Share

2 Responses to 'Boolean portability under Rails'

  1. July 10, 2009 at 19:26
    Eric Mill
  2. April 29, 2010 at 16:29
    Omar Ontiveros