Understand Form Builder in Rails

I want to introduce the basic of how to use form builder in rails. If we have a basic title and description page, if we submit the form without no content, we hope it will show some error message. the haml file will looks like this.

%section.new_todo
%h3 Add a new todo
= form_for @todo do |f|
= f.label :name, "Name"
= f.text_Filed :name
= f.label :description, "Description"
= f.text_area :description, rows: 6
%br
= f.submit "Add this Todo"

Of course you can write if @todo.errors?, then render all the errors out.

But you can put a my_form_builder.rb file in the helpers:

class MyFormBuilder < ActionView::Helper::FOrmBuilder
def label(method, text = nil, options = {}, &block)
errors = object.errors[method.to_sym] #object points to @todo in this case. see more if rails doc.
if errors
text += "<span class=\"error\">#{errors.first}</span>"
end
super(method, text.html_safe, options, &block)
end
end
%section.new_todo
%h3 Add a new todo
= form_for @todo, builder: MyFormBuilder do |f|
= f.label :name, "Name"
= f.text_Filed :name
= f.label :description, "Description"
= f.text_area :description, rows: 6
%br
= f.submit "Add this Todo"

But you have to implement it in every form_for. If you want every formfor you use this feature, you can write your own formfor in application_helper.rb

if you take a look at rails doc:

form_for(record, options = {}, &block) Creates a form that allows the user to create or update the attributes of a specific model object.

It need record, options, &proc. So we create our own form_for also takes this three parameter. But we use ruby hash method: merge!, to put builder directly inside the options hash:

  module ApplicationHelper
def my_form_for(record, options = {}, &proc)
form_for(record, otpions.merge!({builder: MyFormBuilder}), &proc)
end
end

formtastic

It is a simple custom form builder

simpleform:

  • simple_form_for
  • integrate bootstrap, foundation
  • lots of customization
  • default mappings
  • complex.

rails-bootstrap-forms:

  • use f.alert_message to show error
  • also work with bootstrap
  • easy to go
  • like original rails form

Originally published at http://code.hsuancheng.net/understanding-form-builder/ on June 22, 2017.