Rails Radio Button Mystery

Once I have to handle radio buttons in rails, I always need to look up the syntax again – especially of the attributes. So I wanted to print the most important issues down:

At first, we need to know how the normal html radio button behaves. A radio button is an input field with type radio with the following attributes:

  • name: Individual name of the radio button. If many have the same name, they belong to the same group.
  • value: value that is send when submitting the form
  • checked: if the value is checked when loading the page or not

Now looking at the rails function we have the following attributes to the radio_button function:

  • object_name: name of the object that should be set
  • method: name of the method that should be set
  • tag_value: value that should be set
  • options: can set checked: true

Irritating is, that if you use f.radio_button on a form, the object_name parameter is automatically assigned and you only have to specify the other parameters.

Example in bootstrap together with a label:

<div class="form-group">
  <div class="col-sm-8 col-sm-offset-2">
    <div class="radio-inline">
      <% CalendarColor.find_each do |calendar_color| %>
          <%= f.label calendar_color.id do %>
              <%= f.radio_button :color_id, calendar_color.id, checked: calendar_color.default_color %> <%= color.name %>
          <% end %>
      <% end %>