Eric Chu Eric Chu - 2 months ago 14
Ruby Question

how to display each object in array in rails form_for

<%=form_for @question do |f|%>

<%=f.label :name, "Question:"%>
<%=f.text_field :name%>

<%=f.label :answer, "Answer:"%>
<%=f.text_field :answer%>

<%=f.label :wrong_answers%>
<%=f.text_field :wrong_answers, multiple: true%>

<%=f.label :wrong_answers%>
<%=f.text_field :wrong_answers, multiple: true%>

<%=f.label :wrong_answers%>
<%=f.text_field :wrong_answers, multiple: true%>
<%end%>


when I create a question like this,

Question.create(
name: "1+1?",
answer: "2",
wrong_answers: ["1", "4", "3"])


The edit form displays every wrong_answer text fields as ["1", "4", "3"]. My question is how do I get it to display each number on different text fields.

Answer

Try this:

<% @question.wrong_answers.each do |wa| %>
   <%= text_field_tag "question[wrong_answers][]",  wa %>
<% end %>

Instead :

  <%=f.label :wrong_answers%>
  <%=f.text_field :wrong_answers, multiple: true%>

  <%=f.label :wrong_answers%>
  <%=f.text_field :wrong_answers, multiple: true%>

  <%=f.label :wrong_answers%>
  <%=f.text_field :wrong_answers, multiple: true%>