Labels for radio buttons in rails form Labels for radio buttons in rails form ruby-on-rails ruby-on-rails

Labels for radio buttons in rails form


Passing the :value option to f.label will ensure the label tag's for attribute is the same as the id of the corresponding radio_button

<% form_for(@message) do |f| %>  <%= f.radio_button :contactmethod, 'email' %>   <%= f.label :contactmethod, 'Email', :value => 'email' %>  <%= f.radio_button :contactmethod, 'sms' %>  <%= f.label :contactmethod, 'SMS', :value => 'sms' %><% end %>

See ActionView::Helpers::FormHelper#label

the :value option, which is designed to target labels for radio_button tags


<% form_for(@message) do |f| %>  <%= f.radio_button :contactmethod, 'email', :checked => true %>   <%= label :contactmethod_email, 'Email' %>  <%= f.radio_button :contactmethod, 'sms' %>  <%= label :contactmethod_sms, 'SMS' %><% end %>


If you want the object_name prefixed to any ID you should call form helpers on the form object:

- form_for(@message) do |f|  = f.label :email

This also makes sure any submitted data is stored in memory should there be any validation errors etc.

If you can't call the form helper method on the form object, for example if you're using a tag helper (radio_button_tag etc.) you can interpolate the name using:

= radio_button_tag "#{f.object_name}[email]", @message.email

In this case you'd need to specify the value manually to preserve any submissions.