我的单选按钮出现了一些问题。这是我的ruby生成的HTML:
<form accept-charset="UTF-8" action="/uanswers" class="new_uanswer" id="new_uanswer" method="post"><div style="margin:0;padding:0;display:inline">
<input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="tiJsYNr71Zqo+R5TheG2nvB3ownJ4iKbmwMfA/11TXg=" /></div>
<table>
<input id="uanswer_answer_id" name="uanswer[answer_id]" type="hidden" /> <tr>
<td><input id="uanswer_answer_id_12" name="uanswer[answer_id]" type="radio" value="12" /></td>
<td><label for="uanswer_answer_id">!</label></td> <td> | Count: 0</td> </tr> <input id="uanswer_answer_id" name="uanswer[answer_id]" type="hidden" />
<tr>
<td><input id="uanswer_answer_id_13" name="uanswer[answer_id]" type="radio" value="13" /></td>
<td><label for="uanswer_answer_id">!!</label></td> <td> | Count: 0</td> </tr> <input id="uanswer_answer_id" name="uanswer[answer_id]" type="hidden" />
<tr>
<td><input id="uanswer_answer_id_14" name="uanswer[answer_id]" type="radio" value="14" /></td>
<td><label for="uanswer_answer_id">!!!</label></td> <td> | Count: 0</td>
</tr>
</table>
不幸的是,它仅在我选择第三个单选按钮时有效。例如,如果我选择第一个或第二个,则params散列中的“answer_id”字段为空。但是,如果我选择第三个,则它是正确的值:14。 为什么会这样呢? HTML似乎是正确的。
编辑:这是此HTML背后的ERB
<%= form_for(uanswer) do |f| %>
<table>
<% answers.each do |answer| %>
<%= f.hidden_field :answer_id %>
<tr>
<% unless current_user.has_answered? question %>
<td><%= f.radio_button :answer_id, answer.id %></td>
<% end %>
<td><%= f.label :answer_id, answer.answer %></td>
<td> | Count: <%= answer.count %></td>
</tr>
<% end %>
</table>
<% unless current_user.has_answered? question %>
<%= f.submit "Answer!" %>
<% end %>
<% end %>
答案 0 :(得分:1)
answer_id的隐藏字段可能是必要的(如果没有选中单选按钮,它将使服务器清除answer_id),但它被放在错误的位置。它应该不在循环中:
<%= form_for(uanswer) do |f| %>
<table>
<%= f.hidden_field :answer_id %>
<% answers.each do |answer| %>
<tr>
<% unless current_user.has_answered? question %>
<td><%= f.radio_button :answer_id, answer.id %></td>
<% end %>
<td><%= f.label :answer_id, answer.answer %></td>
<td> | Count: <%= answer.count %></td>
</tr>
<% end %>
</table>
<% unless current_user.has_answered? question %>
<%= f.submit "Answer!" %>
<% end %>
<% end %>