Reputation: 1441
In the code below I have used the radio buttons to select one option from Three options,
But, since the name of one radio button is different from other, i can able to select all the three options instead of one
I used this code because, i want to update records with all the three names from text box and its corresponded selected value,
Is there any other work around to do this
View
<% 1.upto(3) do |i| %>
<%= text_field_tag "fields[#{i}][name]",'' %>
<%= radio_button_tag "fields[#{i}][answer]", '1', false%>
<% end %>
Controller
params[:fields].each do |i, values|
u = Sample.new
u.name = values["name"]
u.answer = values["answer"] ? 1 : 0
u.save
end
thanks,
Upvotes: 0
Views: 1391
Reputation: 12643
First of all, nested attributes may be well suited for your problem. I'd recommend looking into those instead of the way you are approaching things now.
If you want to just stick with things the way they are you can make things work with a couple adjustments.
For radio buttons to work correctly you need to use a unique value (i
) for each option:
<%= radio_button_tag "answer", i, false%>
Then in your controller
u.answer = params["answer"] == i ? 1 : 0
Upvotes: 1
Reputation: 1659
You probably want something like this:
<% 1.upto(3) do |i| %>
<%= text_field_tag "fields[#{i}][name]",'' %>
<%= radio_button_tag "fields[answer]", '#{i}', false%>
<% end %>
This will yield an answer field with a value of 1,2, or 3 depending on which one is selected.
Upvotes: 1