我几乎使用了常规脚手架中的代码。唯一的变化是 4.times 块,我在这个问题上制作了 4 个答案对象。原因是我在视图中有相应的输入字段。现在,如果验证失败,它会再次呈现 new.html.erb,但是在我阅读完之后它不会再次调用“新”操作。但是我依赖于 4.times 块,因为否则视图中的循环没有答案可以循环。我该如何解决?我尝试重定向,但错误消息消失了。
新动作
def new
@question = Question.new
4.times do
@question.answers.build
end
respond_to do |format|
format.html # new.html.erb
format.json { render json: @question }
end
end
创建动作
def create
@question = Question.new(params[:question])
respond_to do |format|
if @question.save
format.html { redirect_to @question, notice: 'Question was successfully created.' }
format.json { render json: @question, status: :created, location: @question }
else
format.html { render action: "new" }
format.json { render json: @question.errors, status: :unprocessable_entity }
end
end
end