Radio buttons on Rails
Similar to this question: Checkboxes on Rails
What's the correct way of making radio buttons that are related to a certain question in Ruby on Rails? At the moment I have:
<div class="form_row">
<label for="theme">Theme:</label>
<br><%= radio_button_tag 'theme', 'plain', true %> Plain
<br><%= radio_button_tag 'theme', 'desert' %> Desert
<br><%= radio_button_tag 'theme', 'green' %> Green
<br><%= radio_button_tag 'theme', 'corporate' %> Corporate
<br><%= radio_button_tag 'theme', 'funky' %> Funky
</div>
I also want to be able to automatically check the previously selected items (if this form was re-loaded). How would I load the params into the default value of these?
As in this previous post, with a slight twist:
<div class="form_row">
<label for="theme">Theme:</label>
<% [ 'plain', 'desert', 'green', 'corporate', 'funky' ].each do |theme| %>
<br><%= radio_button_tag 'theme', theme, @theme == theme %>
<%= theme.humanize %>
<% end %>
</div>
Where
@theme = params[:theme]
Same as V's, but has associated labels with each radio button. Clicking the label checks the radio button.
<div class="form_row">
<p>Theme:</p>
<% [ 'plain', 'desert', 'green', 'corporate', 'funky' ].each do |theme| %>
<br><%= radio_button_tag 'theme', theme, @theme == theme %>
<%= label_tag "theme_#{theme}", theme.humanize %>
<% end %>
</div>
Using Haml, getting rid of needless br tags, and nesting inputs within label so that they may be selected without matching labels to ids. Also using form_for. I would consider this to be following best practices.
= form_for current_user do |form|
.form_row
%label Theme:
- [ 'plain', 'desert', 'green', 'corporate', 'funky' ].each do |theme|
%label
= form.radio_button(:theme, theme)
= theme.humanize