Rails Boolean Field Helper 1
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.
Creation:
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
end
end
def self.down
drop_table :table
end
end
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]]) %>
Validation:
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
end
Trackbacks
Use the following link to trackback from your own site:
http://littlebitofcode.com/trackbacks?article_id=6
If only more than 83 people would hear about this..