Boolean button helper


I don’t have a blog, but wanted to share this little bit of code with
other semi-beginners like myself who are still learning to take
advantage of rails features.

Selecting an attribute with a boolean switch is a common pattern in
forms. You can do it with a check box, but radio buttons are more
expressive in some situations and better convey to the user that they
are making a mandatory choice. But doing this with radio buttons
typically takes 5 lines of html: 3 labels and 2 radio buttons.

Here’s a simple boolean button helper that you can put in your custom
form builder.

class YourCustomFormBuilder < ActionView::Helpers::FormBuilder

def boolean_buttons_for(method, label_true = “true”, label_false =
“false” )
@template.label(@object_name, method,
method.to_s.humanize, :class => ‘align’ ) +
@template.radio_button( @object_name, method, true ) +
@template.label( @object_name, method.to_s + “_true”,
label_true ) +
@template.radio_button( @object_name, method, false ) +
@template.label( @object_name, method.to_s + “_false”,
label_false ), :class => “row”)


Then you can create a set of boolean button tags in your view like

<% form_for :person, :builder => YourCustomFormBuilder do |f| %>

<%= f.boolean_buttons_for :happy, “Yes”, “No” %> #DRY

<% end %>

The above assumes you are using a custom form builder and building
your forms with the form_for helper. If you are not using a custom
builder, I assume you could open up the default FormBuilder and stick
it in there. If you’re not using form builders, this code won’t work
for you, but you could follow a similar pattern within
ApplicationHelper or your ControllerHelper. You’ll have to get rid of
@template and @object_name, as they are only available inside the
FormBuilder object.