Rails Boolean Field Helper

Posted by jcnnghm Thu, 07 Feb 2008 22:10:00 GMT

I wrote this some time ago and I thought it was worth reposting here, primarily so it would be easier for me to find. This details the handling of binary fields from front to back in Ruby on Rails.


Active Record migrations are quite good at creating tables. The below migration will add table “table” to the db with a boolean field a_boolean when rake db:migrate is run.

class CreateTable < ActiveRecord::Migration
  def self.up
    create_table :table do |t|
      t.column :a_boolean, :boolean

  def self.down
      drop_table :table

Boolean Form Field Select Helper:

The following line creates a select box with true and false represented by Yes and No. The currently selected value (while editing) is automatically selected.

<%= select('table', 'a_boolean', [["Yes",true],["No",false]]) %>


This validation will confirm that the field is either true or false.

validates_each :a_boolean do |record, attr, value|
  record.errors.add attr, 'is invalid.' if value != true && value != false