This method was tested on Rails 2.2.2.

I am currently building a Rails application where I will need to build some custom form elements and have them still work with the FormBuilder.

I found a post about building a spinbox field that really helped me on my way.

In my application I had a boolean field in the database and I wanted to create a menu select with the options 'Yes' and 'No' with a corresponding '1' or '0' value. I also wanted the option to include the ability to add a blank option as a default using the include_blank syntax that is also found in the DateHelper. For example;

:include_blank => true

OR

:include_blank => ' - Any - '

This would provide me with the normal flexibility of the default select tag.

For my project I need to extend the FormOptionsHelper.

what to do

I started off by creating a file in the lib folder:

my_form_options_helper.rb

RUBY:
  1. module ActionView
  2.   module Helpers
  3.     module FormOptionsHelper
  4.       def boolean_yes_no_select(object_name, method, options = {}, html_options = {})
  5.         choices = {
  6.           'No'  => false,
  7.           'Yes' => true
  8.         }
  9.         InstanceTag.new(object_name, method, self, options.delete( :o bject)).to_select_tag(choices, options, html_options)
  10.       end
  11.     end
  12.  
  13.     class FormBuilder
  14.       def boolean_yes_no_select(method, options = {}, html_options = {})
  15.         @template.boolean_yes_no_select(@object_name, method, objectify_options(options), @default_options.merge(html_options))
  16.       end
  17.     end
  18.   end
  19. end

Next will need to add a line to your 'environment.rb' file:

RUBY:
  1. require 'my_form_options_helper'

This makes the 'boolean_yes_no_select available to your form builder and it allows you to create them independantly of a form builder.

Using it with the form_for method is easy:

RUBY:
  1. f.boolean_yes_no_select :publish, :include_blank => "Any"

I hope this will help others in their rails development.

Development Rails