# Boolean button helper

**URL:** <https://www.ruby-forum.com/t/boolean-button-helper/155085>\
**Category:** Rails\
**Created:** [December 7, 2008, 6:09pm UTC](https://www.ruby-forum.com/t/boolean-button-helper/155085 "2008-12-07T18:09:05Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [December 7, 2008, 6:09pm UTC](https://www.ruby-forum.com/t/boolean-button-helper/155085/1 "2008-12-07T18:09:05Z")

</div>

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.content\_tag(“div”,  
@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”)  
end  
…  
end

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

\<% 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.
