2010-11-11 65 views
7

我有它输出一个选择框如下:导轨 - 单选按钮收集组

<%= f.label :request_type_id %><br /> 
<% requestTypes = RequestType.all %> 
<%= f.collection_select :request_type_id, requestTypes, :id, :title, :prompt => true %> 

什么是轨道的方法,而不是输出单选按钮?

回答

15

对于单选按钮,您必须迭代自己并输出每个单选按钮及其标签。事实上这很容易。

<% RequestType.all.each do |rt| %> 
    <%= f.radio_button :request_type_id, rt.id %> 
    <%= f.label :request_type_id, rt.title %> 
<% end %> 

或者在haml的情况下,它优于ERB:

- RequestType.all.each do |rt| 
    = f.radio_button :request_type_id, rt.id 
    = f.label :request_type_id, rt.title 
+0

谢谢,这工作很好,但我确实需要工作机智h标签使其与单选按钮匹配。 – AnApprentice 2010-11-11 17:36:23

+0

@AnApprentice - 做了一些搜索相同的东西,并找到了这个答案:http://stackoverflow.com/a/4921732/247763 – derekerdmann 2011-12-30 04:11:28

+0

任何想法如何做到这一点,但固定值。我的意思是,而不是'Model..all.each',你有类似于'我在0..5'中? – Sebastialonso 2014-03-25 00:29:33

0

我不认为Rails中有一个默认选项可以实现此目的;幸运的插件是你的朋友,我认为你想要的是非常容易与simple_form

0

这里是你的单选按钮,您可以在下面的这样: -

<%= f.radio_button:request_type_id,'1',{"id","title"} %>id 
<%= f.radio_button:request_type_id,'2',{"id","title"} %>title 
1

使用simple_form宝石:

在控制器中:

@request_types = RequestType.all 

在一种形式中:

<%= f.association :request_type, collection: @request_types, as: :radio_buttons %> 
0

示例如何使用f.collection_radio_buttonsEnum作为一个集合:

<%= f.collection_radio_buttons :reason, MyEnum.statuses.map {|k,v| [k,k]}, :first, :last do |b| %> 
    <div class='your-class'> 
    <%= b.radio_button %> 
    <%= b.label %> 
    </div> 
<% end %>