Thursday, March 15, 2012

Activerecord Boolean False Gotcha

Unless you've got a good reason not to, when you declare a boolean field in Rails/ActiveRecord, always set give it a default and disallow null. Eg:

 t.boolean "troublemaker", :default=> false, :null => false

The reason for this is that when you want to search on it later to see if it's false, you can simply say:

Student.where( :troublemaker => false)

The above statement won't find students where the :troublemaker is null so it's a good thing you didn't allow that to happen.

If you already have boolean fields in your DB that may have null values which you were regarding as false, it's easily fixed. Just run a migration like:


class DefaultTroublemakerToFalseForStudents < ActiveRecord::Migration

  def self.up
    change_column_default :students, :troublemaker, false
    Student.where(:troublemaker => nil).each {|s| s.completed = false; s.save!}
  end

  def self.down
    change_column_default :students, :troublemaker, nil
  end

end