渲染不会执行操作

时间:2012-08-09 10:24:59

标签: ruby-on-rails ruby ruby-on-rails-3

我几乎使用常规脚手架中的代码。唯一的变化是4次块,我在这个问题上做了4个答案对象。原因是我在视图中有相应的输入字段。现在,如果验证失败,它会再次呈现new.html.erb,但是在我阅读之后它不会再次调用“new”操作。但是我依赖于4次块,因为否则视图中的循环没有循环的答案。我该如何解决?我尝试重定向,但错误消息消失了。

新动作

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

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

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