How to Generate Labels for Radio Buttons in Rails

Friday, July 3rd, 2009

This is the code that I got from the Rails API, however, the value was processed as an HTML attribute rather than the value of the radio button.

<% form_for @review do f %>
  <%= f.label :rating, 1, :value => 1 %>
  <%= f.radio :rating, 1 %>
<% end %>

Undesired output:

<label for="review_rating" value="1">1</label>
<input id="review_rating_1" name="rating" type="radio" value="1" />

Here’s the code that works thanks to a few Google searches.

<% form_for @review do f %>
  <%= f.label :rating_1, 1 %>
  <%= f.radio :rating, 1 %>
<% end %>

Desired output:

<label for="review_rating_1">1</label>
<input id="review_rating_1" name="rating" type="radio" value="1" />

Thanks to Rails API FormHelper and Labels for radio buttons in rails form.

Leave a Response

You must be logged in to post a comment.