我在 Rails 中有一个调查表单,它循环遍历数据库表中的问题,并为每个问题生成一组单选按钮(答案选择)。
每组单选按钮应该有不同的
name
值,并且提交会在 Answers
表中为每个答案创建一条新记录。
但是,我收到
ParameterMissing
错误,因为表单发送:
Parameters: {"authenticity_token"=>"[FILTERED]","answer_value_0"=>"1", "commit"=>"SAVE"}
而不是:
Parameters: {"authenticity_token"=>"[FILTERED]", "answer"=>{"answer_choice"=>"1"}, "commit"=>"SAVE"}
表格看起来像:
<%= form_with model: @answers, url: answers_path do |ans|%>
<% @questions.each_with_index do |question, index| %>
<div>
<%= ans.radio_button :answer_choice, 1, name: "answer_value_#{index}"%>
<%= ans.label :answer_value_1, "Yes" %>
</div>
<%end%>
<%= ans.submit "SAVE" %>
<%end%>
控制器称为
SurveyResultsController
,看起来像:
def show
@answers = Answer.new
@survey = Survey.find(params[:id])
@questions = @survey.questions
end
def create
@survey = Survey.find_by(params[:id])
@answers = Answer.new(answer_params)
if @answers.save
redirect_to root_url
else
redirect_to show_survey_path(@survey)
end
end
def answer_params
params.require(:answer).permit(:answer_choice)
end
将字段名称从
"answer_value_#{index}"
更改为 "[answer]answer_value_#{index}"
。它将用 answer
键包裹参数