UPDATE: THE CODE IN THIS开发者_Python百科 POST HAS BEEN CHANGED TO THE WORKING SOLUTION.
To make radio buttons display stored values from a mapped array.
Controller:
@questions = Question.all
@ans = Answer.where(user_id = current_user.id)
@answers = @questions.map { |q| [q, @ans.find_by_question_id(q.id)] }
View:
<% @answers.each do |q| %>
<%= q[0].question %> [<%= q[1].id %>] <%= q[1].score %>
<% [ 1, 2, 3, 4, 5 ].each do |f| %>
<%= radio_button_tag q[0].name, f, f == q[1].score %>
<% end %>
<br />
<% end %>
edit: oops... forgot the @ on answers.each. fixed
<% @answers.each do |q| %>
<%= q[0].question %>
<% [1..5].each do |f| %>
<%= radio_button_tag 'score', f, (f == q[1].score).to_s %>
<% end %>
<br />
<% end %>
Its off the top of my head but basically you have to pass true or false not the number checked. I'm assuming that q[1].score is a number from 1 to 5
Hey, folks. Thanks for your help. Mike, you were close. There were two problems. First, the name "score" would be assigned to every button for every question. The name needs to be the same for every button for one question, but needs to change on the next question. See q[0].name below. Second, the score is numerical, not a string. So "to_s" resulted in every button being checked as it was made. Since there could only be one button checked per set, checking every button resulted in the last button being checked for each set. (e.g. the score 5 being checked each time)
<% @answers.each do |q| %>
<%= q[0].question %> [<%= q[1].id %>] <%= q[1].score %>
<% [ 1, 2, 3, 4, 5 ].each do |f| %>
<%= radio_button_tag q[0].name, f, f == q[1].score %>
<% end %>
<br />
<% end %>
精彩评论