setting radio button = checked from controller
I have four radio buttons as follows:-
<%= radio_button_tag ch,@choices[0].id %><%= label_tag :cid, @choices[0].Option %>
<%= radio_button_tag ch,@choices[1].id %><%= label_tag :cid, @choices[1].Option %>
<%= radio_button_tag ch,@choices[2].id %><%= label_tag :cid, @choices[2].Option %>
<%= radio_b开发者_开发百科utton_tag ch,@choices[3].id %><%= label_tag :cid, @choices[3].Option %>
I want to set one of the radiobutton to be checked based on @choices[1].id. How can I do it from the controller?
This is not really an answer to your question but because you haven't had any other answers I'm going to throw this out there.
First, most people wouldn't do what you're doing.
Second, it doesn't make sense to want to do precisely what you're asking. Ie. to set the radio button based on the the value of @choices[1].id
. Maybe you meant something like "the value of @choice.id
"?
Anyway, back to "First" - how would most people do it?
Most people would use the radio_button
helper, not the radio_button_tag
helper. So, how to do this? Well what you need from your controller is a single object that you will call a method on to get/set one of the values you have in your radio group. Usually this is a model object which has a belongs_to
association with some other model. Like you might have:
class Customer < ActiveRecord::Base
belongs_to :contact_method
end
You're going to allow them to select which ContactMethod
they want to use, so assuming you have a @customer
set in your controller, your radio buttons would be like this:
<% ContactMethod.all.each do |cm| %>
<%= radio_button :customer, :contact_method_id, cm.id %>
<%= label :customer, :contact_method_id, cm.name, :value => cm.id %>
<% end -%>
That will create as many radio buttons as you have ContactMethod
s and it will automatically mark one as checked if @customer.contact_method
has a value that matches one of those ContactMethod
s
精彩评论