How can I loop through an array of objects 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 %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With