Rails 3:数组中每个元素的单选按钮

时间:2011-08-11 19:44:12

标签: ruby-on-rails

如何在一个对象数组中循环并为表单中的每个对象创建一个单选按钮或复选框?

2 个答案:

答案 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 %>