开发者

Rails - Radio Buttons for collection sets

I have the following which outputs a select box:

<%= f.label :request_type_id %><br />
<% reques开发者_如何学CtTypes = RequestType.all %>
<%= f.collection_select :request_type_id, requestTypes, :id, :title, :prompt => true %>

What is the rails method to instead output Radio Buttons?


For radio buttons you have to iterate yourself and output every radio button and its label. It's really easy in fact.

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

Or in haml in case it's preferred over erb:

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


In Rails 4 there is a collection_radio_buttons for this:

<%= f.collection_radio_buttons :request_type_id, RequestType.all, :id, :title %>


An example how to use f.collection_radio_buttons with an Enum as a collection:

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


Using simple_form gem:

In controller:

@request_types = RequestType.all

In a form:

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


I don't think there is a default option in Rails to achieve this; luckily plugins are your friend and I think that what you want is very easy with simple_form.


Here's your radio button you can the below as such :-

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜