Forum: Ruby on Rails boolean button helper

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
A822370edefad22484f9260fb787c710?d=identicon&s=25 Ed (Guest)
on 2008-12-07 18:09
(Received via mailing list)
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.
This topic is locked and can not be replied to.