我需要有关错误验证/重定向的帮助....
如果我使用format.html {redirect_to :back, flash: {error: "Oops, something went wrong. Please try again."}
错误消息有效,但它不保存表单数据,因此用户需要重新输入并且不知道哪些字段不正确。
format.xml {render :xml => @award.errors, :status => :unprocessable_entity}
行重定向到后面,但没有显示任何错误。
我想查看哪些字段不正确,其验证消息完好无损。请帮助语法。提前谢谢!
respond_to do |format|
if @award.save
format.html { redirect_to(new_award_path, :notice => 'Thank you for your nomination!') }
format.xml { render :xml => @award, :status => :created, :location => @award }
else
format.html {redirect_to :back}
#format.html {redirect_to :back, flash: {error: "Oops, something went wrong. Please try again."}}
format.xml {render :xml => @award.errors, :status => :unprocessable_entity}
end
end
更新以包含更多详细信息:
我正在为这个创建方法使用两种不同的形式。每个表单都有一个隐藏字段来设置一个布尔值,然后我根据隐藏条件在我的控制器中做东西。如果有错误,我需要重定向到正确的表单,保持其值,并显示相应的错误字段。像这样:
respond_to do |format|
if @award.save
format.html { redirect_to(new_award_path, :notice => 'Thank you for your nomination!') }
format.xml { render :xml => @award, :status => :created, :location => @award }
else
if boolean_field == true
format.html { render action: "true_form" }
format.xml {render :xml => @award.errors, :status => :unprocessable_entity}
else
format.html { render action: "false_form" }
format.xml {render :xml => @award.errors, :status => :unprocessable_entity}
end
end
end
当我以这种方式尝试时,错误起作用,但它总是返回到true_form,即使我开始使用false_form。所以,就像它忽略了boolean_field条件......有意义吗?
答案 0 :(得分:2)
当有错误时,技巧不会重定向,而只是再次渲染视图。
respond_to do |format|
if @award.save
format.html { redirect_to(new_award_path, notice: 'Thank you for your nomination!') }
format.xml { render xml: @award, status: :created, location: @award }
else
format.html { render action: 'new' }
format.xml { render json: @award.errors, status: :unprocessable_entity }
end
end