【问题标题】:Why does validation error appear on the form after successful submit and going back?为什么提交成功返回后表单上会出现验证错误?
【发布时间】:2014-09-09 14:40:32
【问题描述】:

我正在使用 Rails 4 和 Chrome。结果如下:

  1. 发布导致验证错误的表单(即“名称不能为空”)
  2. 通过更正输入成功发布相同的表单
  3. 点击浏览器后退按钮,步骤 1 中的验证错误会显示在输入字段中,即使它的值不为空

为什么会弹出第 1 步中的验证错误以及如何解决此问题?注意:Turbolinks 正在使用中,可能是这个原因吗?

复制方法如下:

rails g scaffold Page name:string

class Page < ActiveRecord::Base
  validates :name, presence: true
end
Navigate to /pages/new
Submit (errors appear on the form)
Fillout the name
Submit again (redirected to successfully created model)
Hit the browser back button (the validation errors are there, and the field is filled with the last supplied value)

【问题讨论】:

    标签: ruby-on-rails google-chrome form-submit back-button validationerror


    【解决方案1】:

    我猜您正在使用类似于以下代码的代码来发回与正在创建/更新的记录相关的错误:

    def update
      @post = Post.find(params[:id])
      if @post.update_attributes(post_params)
        # your logic when successfull
      else
        render :edit, flash[:errors] = @post.errors
      end
    end
    

    或类似的东西。我的意思是,您应该使用以下语法来设置 flash 中的错误:

    flash.now[:errors] = @post.errors
    

    (1)这应该设置flash[:errors]仅适用于当前页面,并在您离开此页面后立即将其删除。

    (2)您也可以在视图末尾使用flash.clear,但这不是应该的方式,而且看起来有点“hacky”。​​ p>


    资源:

    【讨论】:

    • 嘿伙计!我没有使用 Flash 消息,只是标准 Rails 表单和模型验证。
    • 添加了一个例子来说明情况!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-05-10
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-03
    • 1970-01-01
    相关资源
    最近更新 更多