0

我几乎使用了常规脚手架中的代码。唯一的变化是 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
4

2 回答 2

0

您需要查看的是@question在您的创建操作中。从理论上讲,它应该包含 4 个新建的答案,因此重新显示表单也将包含这些。

如果它们没有被写入,您可能需要查看Accepts_nested_attributes_for以确保它从请求中正确反序列化。

于 2012-08-09T11:00:58.317 回答
0

正如您的标题所暗示的那样:render只渲染(属于的模板)动作而不执行动作本身。

要在失败的创建调用中再次呈现您的预建答案,我建议:reject_if从嵌套属性设置中删除条件。这样,将保留提交的空答案。为了防止它们被写入数据库,只需向 Question 模型添加常规验证...

于 2012-08-09T12:26:25.533 回答