lundi 20 février 2017

Ruby form, radio buttons group name: causing an issue in accessing the value

I am working on a form which essentially saves a set of answer rows.

 def              
          answer_row_params(my_params)
                    my_params.permit(:assessment_id,:little_heart_id,:concept_id,:question_id, :answer_id)
    end
        def new
       @assessment = Assessment.find(params[:assess])
       @little_heart = LittleHeart.find(params[:little_heart])
       len = 0
       @assessment.concepts.each do |concept| 
          concept.questions.each do |question| 
          len = len + 1
       end
    end
    @answers = []
    len.times do
    @answers << AnswerRow.new
    end
    end 
    def create
        params["answer_rows"].each do |answer|
        AnswerRow.create(answer_row_params(answer))
       end
    end

If I have to explain what I am trying to achieve, I have an assessment which is assigned to a little hear(child), the assessment has multiple concepts, each concept has multiple questions and each question has 4 answers. I am trying to read assessment id, little_heart_id, concept_id, question_id and answer_id. It is going successfully till the last but one field. I am using radio buttons for answers. So the name: become "answer_rows[][answer_id]" for all the radio buttons. So this makes select only one answer among all the questions causing empty entry for the answer for all the questions except for the one chosen.

I tried making the name unique to each group of answers by doing name: "answer_rows[][answer_id][#{question.id}]". This allows selecting one answer per question. But because, the name: has something else appended to answer_rows[][answer_id], the answer is again going empty to all the fields. How can I make the names unique and still retain the way to access the answer that user has chosen?

Below is what the form looks like (I have not provided the complete view, but I believe this enough to make out what I am trying to do):

<%= form_tag answer_rows_path do %>
      <%= fields_for 'answer_rows[]', answer_row do |answer| %>
       <%= answer.hidden_field(:little_heart_id, :value => @little_heart.id) %>
            <%= answer.hidden_field(:assessment_id, :value => @assessment.id) %>

            <%= answer.hidden_field(:concept_id, :value => concept.id) %>
            <%= answer.hidden_field(:question_id, :value => question.id) %>

            <%= answer.hidden_field :answer_id%>
            <%question.answers .each do |ans| %>
                <%= answer.radio_button :answer_id, ans.id%>
            <%end%>

Aucun commentaire:

Enregistrer un commentaire