Rails 3: radio button for each element in an array
How can I loop through an array of obje开发者_如何学Gocts and create a radio button or check box for each of them in a form?
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 %>
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 %>
精彩评论