validation - Rails 3.2-验证-重定向回错误

标签 validation error-handling ruby-on-rails-3.2

我需要有关错误验证/重定向的帮助。...

如果我使用format.html {redirect_to :back, flash: {error: "Oops, something went wrong. Please try again."},则错误消息有效,但是它不包含表单数据,因此用户需要重新输入并且不知道哪些字段不正确。
format.xml {render :xml => @award.errors, :status => :unprocessable_entity}行重定向到back,但不显示任何错误。

我想查看哪些字段不正确,且其验证消息完整无缺。请帮助语法。提前致谢!

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 

更新以包括更多详细信息:

我为此创建方法使用了2种不同的形式。每个表单都有一个用于设置 bool(boolean) 值的隐藏字段,然后我根据该隐藏条件在 Controller 中进行操作。如果有错误,我需要重定向到正确的表单,保留其值,并显示适当的错误字段。像这样:
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

当我以这种方式尝试时,错误会起作用,但是即使我从false_form开始,也总是返回true_form。因此,这就像忽略了boolean_field条件...有意义吗?

最佳答案

诀窍不是在出现错误时重定向,而只是再次渲染 View 。

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

关于validation - Rails 3.2-验证-重定向回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16525888/

相关文章:

正则表达式匹配 "whole word"返回异常

error-handling - Sitecore 重定向错误

c# - 如何防止ServiceStack EventLogFactory记录DEBUG事件?

mysql - 从sqlite3切换到mysql后ActiveRecord::ConnectionNotEstablished

ruby-on-rails - 带有 nokogiri 的空 html

jquery - jQuery Mobile 表单的自定义验证警报

c# - 为什么我的 XML 验证对其架构失败?

c# - MVC C# 中的验证

Azure数据工厂: Handling inner failure in until/for activity

ruby-on-rails - gem 的未初始化常量