开发者

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 %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜