I have the following create action:
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
However the HTTP response stored in the res variable can have a 200 code, or a 400 code that indicates a Bad Request. I want that if the res.code is 400, it also goes back to the new action with a warning message.
I tried including that condition on the respond_to if like below, but it didn’t worked. It seems that after creating the instance it redirected to edit action. It makes no sense.
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
What would be the correct way to do it?
It’s a bit of a complicated workflow, but it looks like if res’s status is 400, you just want to render the new form again. So you can early escape using the below: