0

私は次のcreate行動をとっています:

def create

  @report = Report.new(params[:report])
  @file = params[:report][:data_file]


  res = @report.get_report(@file, @report.year, @report.month)

  file = open('report.pdf','wb')
  file.write(res.body)

  @report.file = file

  respond_to do |format|
    if @report.save
      format.html { redirect_to @report, notice: 'Report was successfully created.' }
      format.json { render json: @report, status: :created, location: @report }
    else
      format.html { render action: "new" }
      format.json { render json: @report.errors, status: :unprocessable_entity }
    end
  end

end

resただし、変数に格納されているHTTP応答には、200コード、または400不正な要求を示すコードを含めることができます。が400の場合、警告メッセージとともにアクションres.codeに戻ることを望んでいます。new

以下のようにrespond_toにその条件を含めてみましたが、うまくいきませんでした。editインスタンスを作成した後、アクションにリダイレクトされたようです。意味がない。

  respond_to do |format|
    if @report.save and res.code == 200
      format.html { redirect_to @report, notice: 'Report was successfully created.' }
      format.json { render json: @report, status: :created, location: @report }
    else
      format.html { render action: "new" }
      format.json { render json: @report.errors, status: :unprocessable_entity }
    end
  end

それを行う正しい方法は何でしょうか?

4

1 に答える 1

2

少し複雑なワークフローですが、resのステータスが400の場合は、新しいフォームをもう一度レンダリングしたいようです。したがって、以下を使用して早期に脱出することができます。

  if res.status != 200
    render :new
    return
  end
  respond_to do |format|
    if @report.save
      format.html { redirect_to @report, notice: 'Report was successfully created.' }
      format.json { render json: @report, status: :created, location: @report }
    else
      format.html { render action: "new" }
      format.json { render json: @report.errors, status: :unprocessable_entity }
    end
  end
于 2012-06-10T04:22:51.487 に答える