【问题标题】:Keeping validation errors after redirect from partial back to the same page that has the partial从部分重定向回具有部分的同一页面后保持验证错误
【发布时间】:2025-12-19 18:55:12
【问题描述】:

所以我试图从我的表单中获取错误,该表单在我的 root_path 中呈现为部分内容。在我尝试发布它并且它失败(或成功)之后,我想重定向回 root_path。但是,redirect_to 决定不保存任何验证信息。

想知道如何做到这一点。

class PostsController < ApplicationController
  def new
    @post = Post.new
  end

  def create
    @nom = current_user.noms.build(params[:nom])
    if @nom.save
      flash[:success] = "Nom created!"
      redirect_to root_path
    else
      flash[:error] = @nom.errors
      redirect_to root_path
  end

在我的主页/索引中,我以帖子的形式呈现部分内容。

= form_for [current_user, @post] do |f|
  = f.text_field :name
  = f.select :category
  = f.text_area :description
  = f.submit "Post", class: "btn btn-primary"

  - @post.errors.full_messages.each do |msg|
    %p
      = msg

它应该在重定向到根路径后将错误保留在表单的底部。

我还想保留验证失败后的信息。

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    在这种情况下你不应该使用重定向,而是使用渲染:

    class PostsController < ApplicationController
      #..
    
      def create
        @nom = current_user.noms.build(params[:nom])
        if @nom.save
          flash[:success] = "Nom created!"
          redirect_to root_path
        else
          flash[:error] = @nom.errors
          render :template => "controller/index"
        end
      end
    

    controller/index 替换为您的控制器和操作的名称

    也可以查看question

    【讨论】:

    • 虽然这种工作...问题是它只重新呈现部分而不是整个页面。此外,它似乎重定向到 user/1/posts。
    • 我不确定redirect_to root_path and return 是否按照我想要的方式工作。在尝试从 root_path 上的部分表单发布 Post 之后,我希望它返回到 root_path,意思是 home/index。当我render template: '/home/index' 时它可以工作,但它会转到'user/1/posts',我只想让它回到 root_path,所以...'/'
    • 是的,如果它对您来说比 mb 有问题,请尝试在表单中使用 = form_for [current_user, @post], :remote =&gt; true do |f|。但是你应该用respond_to js在create action中实现一些逻辑。
    【解决方案2】:

    这似乎对我有用

    format.html { redirect_to :back, flash: {:errors => "Document "+@requested_doc.errors.messages[:document][0] }}
    

    我不知道这是否会导致任何其他异常问题。

    【讨论】:

      【解决方案3】:

      您不能使用 redirect_to 来显示对象的错误消息,因为在重定向时它会丢弃与 error_messages 链接的对象并使用新对象来重定向路径。

      所以在这种情况下,您只需要使用 render

      respond_to do |format|
              format.html { 
                flash[:error] = @account.errors.full_messages.join(', ')
                render "edit", :id => @account._id, sid: @account.site._id
              }
      end
      

      【讨论】: