I have a partial form that displays a questionnaire. Each question has
a group of radio buttons associated with it which allow the user to
select only one possible answer. In order to do this, I am using a
combination of ‘form_for’ and ‘radio_button’ as shown below. My problem
is, "how do I dynamically pass a value to one of the radio buttons so
that it is checked when the form first renders? Below is a snippet of
the code I am using in the partial form.
<% form_for :questionnaire, @questionnaire do |f| %>
My question is bla, bla, bla?
<%= f.radio_button :field_name, “Y” %>The answer is yes.
<%= f.radio_button :field_name, “N” %>The answer is no.
<% end %>
How does one populate the radio button values from an array of stored
values?
For example, I have a form containing questions and answers associated
with radio buttons. The values selected (by radio button) get stored in
a database. Later, someone wants to change the answers. How do we go
about setting the radio button values in the edit form?
Going back to my previous code example:
<% form_for :questionnaire, @questionnaire do |f| %>
My question is bla, bla, bla?
<%= f.radio_button :field_name, “Y” %>The answer is yes.
<%= f.radio_button :field_name, “N” %>The answer is no.
<% end %>
The above code produces the following HTML:
My question is bla, bla, bla?
Yes
No
The above works fine when I submit and save the data. However, when I
later try to retrieve and edit the data, I have problems. Specifically,
when I try to pass the ‘edit’ form an instance variable containing the
questionnaire hash: @questionnaire = {:field_name => “Y”}
I get an error message like this: undefined method `field_name’ for
{“field_name”=>“Y”}:HashWithIndifferentAccess
<% form_for :questionnaire, @questionnaire do |f| %>
My question is bla, bla, bla?
<%= f.radio_button :field_name, “Y” %>The answer is yes.
<%= f.radio_button :field_name, “N” %>The answer is no.
<% end %>
That should do it. The radio_button helper will mark the appropriate
button based on the value of @questionnaire.field_name. The first will
be marked if the value is “Y” and the second will be marked if the
value is “N”. To get a default value, assign it when you create @questionnaire in your controller:
<% form_for :questionnaire, @questionnaire do |f| %>
My question is bla, bla, bla?
<%= f.radio_button :field_name, “Y” %>The answer is yes.
<%= f.radio_button :field_name, “N” %>The answer is no.
<% end %>
That should do it. The radio_button helper will mark the appropriate
button based on the value of @questionnaire.field_name. The first will
be marked if the value is “Y” and the second will be marked if the
value is “N”. To get a default value, assign it when you create @questionnaire in your controller: