Multiple sets of radio buttons in a rails view
Asked Answered
S

3

5

Is there a way to set up two groups of radio buttons in Rails? I can imagine you could put them into separate forms perhaps but is there a way to create two sets of radio buttons within one form?

Selfexcited answered 10/2, 2011 at 21:42 Comment(0)
E
6

Yes, you can create two different sets by simply using a different radio-button name:

radio_button_tag 'gender', 'male'
radio_button_tag 'gender', 'female'

radio_button_tag 'food', 'none'
radio_button_tag 'food', 'vegetarian'
radio_button_tag 'food', 'vegan'

This will result in params[:gender] being 'male' or 'female' and params[:food] being 'none', 'vegetarian' or 'vegan'. You can do the same thing with the radio_button function.

Eklund answered 10/2, 2011 at 21:47 Comment(0)
E
2

Radio buttons with the same name attributes are grouped. So make sure your Rails code uses the same names for the radio buttons within a group.

According to the documentation the first parameter of the radio_button method is the name, so keep this parameter the same.

Embryotomy answered 10/2, 2011 at 21:50 Comment(0)
E
0

My suggestion is to use radio_button_tag with simple loop. Here you can map the selected value without having a corresponding model by using form_tag.

<%= form_tag methods: :post do  %>
  <% (0..10).each do |value| %>
    <%= radio_button_tag 'store', value, :required => true %>
  <% end %>
  <%=  submit_tag 'submit' %>
<% end %>
Evidence answered 28/5, 2015 at 9:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.