如何在一个对象数组中循环并为表单中的每个对象创建一个单选按钮或复选框?
答案 0 :(得分:15)
无线电广播
<% ["Peter", "Jhon", "Carl"].each do |item| %>
<%= f.radio_button :name, item %> <%= item %><br />
<% end %>
复选框:
<% ["Peter", "Jhon", "Carl"].each do |item| %>
<%= f.check_box :name, item %> <%= item %><br />
<% end %>
答案 1 :(得分:1)
如果您的项目是哈希值,例如您存储在类中的常量:
# 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 %>