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?
Multiple sets of radio buttons in a rails view
Asked Answered
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.
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.
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 %>
© 2022 - 2024 — McMap. All rights reserved.