Writing a custom FormBuilder in Rails 4.0.x

Ruby on rails For my tutorial application on Rails I wanted to use the Bootstrap 3 form layout instead of the one offered by form_for.

Since my needs where simple, I avoided special gems (like Formtastic or Simple_Form) and developed a custom FormBuilder to do the job.

The documentation about is good but was not enough for me, the basic structure is easy to understand:

  • Extend ActionView::Helpers::FormBuilder
  • Define a custom method or…
  • …override superclass methods

Therefore the result should be something like this structure:

class MySuperFormBuilder < ActionView::Helpers::FormBuilder

 # Defining a new method for the custom FormBuilder
 def better_text_field(method, options = {})
  #your custom code goes here

 # Overriding a superclass method
 def text_field(method, options = {})
  #your custom code goes here


Having defined your new FormBuilder you need to call it inside the form_for like this:

<% form_for( ... , :builder => MySuperFormBuilder ) do |f| %>

Or you can force it globally by adding this line into your application.rb file:

ActionView::Base.default_form_builder = MySuperFormBuilder

This is more like an exercise than something that you would need to do on a per-project base, you can find my custom implementation on GitHub.