Frage

I'm new to Rails and have been plugging away at this problem without success. I have a form for users to submit answers to multiple choice questions through radio buttons, and I would like their chosen answers to show up again when they revisit the question or on page reload. Their answer is stored in the database, through the TestQuestions model, in an answer_id column. The following code makes the last radio button checked instead of their given answer, Any suggestions on how to make the default value their answer from the database?

As per my comment below, I think this may require jQuery/javascript to compare the input value in the html ie -

<input id="answer_id_5" type="radio" value ="5" name="answer_id"></input> 

to the database entry.

show.html.erb

<%= form_tag({controller: "test_questions", action: "update"}, method: "patch") do %>

  <% @test_question.question.answers.each do |answer| %>
    <li>
    <%= radio_button_tag "answer_id", answer.id, checked: @test_question.answer_id  %> # THE PROBLEM LINE 
        <%= answer.content %>
    </li>
  <% end %>
  <%= submit_tag "Next"  %>
<% end %>

test_questions_controller.rb

def show
  @test_question = @test_questions.find(params[:id])
end
War es hilfreich?

Lösung

You should do it like this:

<%= radio_button_tag "answer_id", answer.id, checked: @test_question.answer_id == answer.id %>

This:

@test_question.answer_id == answer.id

will return either true or false, thus checking or unchecking the radio button.

@test_question.answer_id returns an integer > 0, which is a truthy value, meaning you're checking all the radio buttons. Since only one radio button can be checked, it'll be the last one.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top