我正在尝试制作一个测验模块,其中记录每个多项选择题的答案并将其追溯到相应的用户。由于编辑和新视图都使用相同的表单,因此我使用了部分。
当我尝试查看新视图时,我得到一个参数错误说"表格中的第一个参数不能包含nil或为空"
控制器是:
class QuizBsController < ApplicationController
before_action :require_sign_in
def show
@quiz_bs = QuizBs.find(params[:id])
end
def new
@quiz_bs = QuizBs.new
end
def create
@quiz_bs = QuizBs.new
@quiz_bs.bs01 = params[:quiz_bs][:bs01]
@quiz_bs.bs02 = params[:quiz_bs][:bs02]
@quiz_bs.bs03 = params[:quiz_bs][:bs03]
@quiz_bs.bs04 = params[:quiz_bs][:bs04]
@quiz_bs.bs05 = params[:quiz_bs][:bs05]
@quiz_bs.bs06 = params[:quiz_bs][:bs06]
@quiz_bs.user = current_user
if quiz_bs.save
flash[:notice] = "Quiz results saved successfully."
redirect_to user_path(current_user)
else
flash[:alert] = "Sorry, your quiz results failed to save."
redirect_to welcome_index_path
end
end
def update
@quiz_bs = QuizBs.find(params[:quiz_bs])
@quiz_bs.assign_attributes(quiz_bs_params)
if @quiz_bs.save
flash[:notice] = "Post was updated successfully."
redirect_to user_path(current_user)
else
flash.now[:alert] = "There was an error saving the post. Please try again."
redirect_to welcome_index_path
end
end
private
def quiz_bs_params
params.require(:quiz_bs).permit(:bs01, :bs02, :bs03, :bs04, :bs05, :bs06)
end
end
新观点是:
<div class="container">
<div id="quiz_bs_new" class="text-center">
<h1>Body Structure Quiz</h1>
</div>
<%= render partial: "quiz", locals: { quiz: @quiz_bs } %>
</div>
<div class="buffer-50"></div>
这是我的形式部分:
<%= form_for @quiz do |f| %>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<%= f.label "Question Text" %><br>
<div class="radio left-padding-30">
<%= f.radio_button :bs01, '1'%><label>31 Seconds or More</label><br>
<%= f.radio_button :bs01, '2'%><label>26 - 30 Seconds</label><br>
<%= f.radio_button :bs01, '3'%><label>21 - 25 Seconds</label><br>
<%= f.radio_button :bs01, '4'%><label>16 - 20 Seconds</label><br>
<%= f.radio_button :bs01, '5'%><label>10 - 15 Seconds</label><br>
<%= f.radio_button :bs01, '6'%><label>6 - 9 Seconds</label><br>
<%= f.radio_button :bs01, '7'%><label>0 - 5 Seconds</label>
</div>
</div>
</div> <!-- column end -->
</div> <!-- row end -->
<div class="buffer-25"></div>
<div class="row">
<div class="col-xs-12 center-block">
<div class="center-block"><%= f.submit %></div>
</div> <!-- column end -->
</div> <!-- row end -->
<% end %>
答案 0 :(得分:1)
变量作为局部变量传递给partials。在表单部分中使用quiz
代替@quiz
可以解决问题。
修改强>
还要在form_for中设置url,以确保表单路由到正确的控制器操作:
form_for quiz, url: quiz_bs_path, method: :post
并将quiz_bs_path
替换为QuizBsController #create