Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3: radio button for each element in an array

How can I loop through an array of objects and create a radio button or check box for each of them in a form?

like image 413
Mexxer Avatar asked Aug 11 '11 19:08

Mexxer


2 Answers

Radios

<% ["Peter", "Jhon", "Carl"].each do |item| %>
  <%= f.radio_button :name, item %> <%= item %><br />
<% end %>

check boxes:

<% ["Peter", "Jhon", "Carl"].each do |item| %>
  <%= f.check_box :name, item %> <%= item %><br />
<% end %>
like image 182
fl00r Avatar answered Nov 08 '22 04:11

fl00r


And if you have your items are in a hash, for instance in a constant that you store in the class:

# fruits.rb

# Fruit has a field 'kind' which is stored as an integer but displayed as a string:
KINDS={0=>'bananas',1=>'plantains',2=>'baby bananas'}


#fruits/new.html.erb

<% Fruit::KINDS.each do |val,name| %>
  <%= f.radio_button :kind, val %> <%= name %><br />
<% end %>
like image 1
Danny Avatar answered Nov 08 '22 04:11

Danny