I built an view to create question and answer. This is my Question and Answer model:
class Question < ActiveRecord::Base
attr_accessible :content
belongs_to :topic
belongs_to :user
belongs_to :question_type
has_many :answers, dependent: :destroy
accepts_nested_attributes_for :answers
end
class Answer < ActiveRecord::Base
attr_accessible :content
belongs_to :question
end
My answer model also have a attribute called correct type boolean to set true if which answer is correct, default is false. I have built a form to create a True/False question:
<%= simple_form_for @question do |q| %>
<%= q.input :content, input_html: { rows: 3, class: 'span6' } %>
<%= q.input :mark, input_html: { class: 'span1' } %>
<%= q.association :topic %>
<%= q.association :question_type %>
<%= q.simple_fields_for :answers do |a| %>
<%= a.input :correct, collection: [[true, 'True'], [false, 'False']],
as: :radio_buttons,
label: 'Answer',
value_method: :first,
label_method: :last,
item_wrapper_class: 'inline'
%>
<% end %>
<% end %>
The correct attribute when rendered in view have these html:
<label class="radio inline"><input class="radio_buttons optional" id="question_answers_attributes_0_correct_true" name="question[answers_attributes][0][correct]" type="radio" value="true">True</label>
<label class="radio inline"><input checked="checked" class="radio_buttons optional" id="question_answers_attributes_0_correct_false" name="question[answers_attributes][0][correct]" type="radio" value="false">False</label>
Now in controller i want to check which radio button is checked and its value. Is there any method to check if correct attribute is checked and its value in controller?
You have to iterate over the params[:question][:answers_attributes] to check radio button checked or not. You can do something like this,
This will return an array of answer attributes which are corrected as true.