从部分重定向返回到具有部分的同一页面后保持validation错误

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

想知道怎么做。

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 

在我的主页/索引中,我渲染了postforms的部分内容。

 = 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 

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

我还想在validation失败后保留那里的信息。

在这种情况下,您不应该使用重定向,而是使用render:

 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替换为您的控制器和操作的名称

还要检查这个问题

这似乎对我有用

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

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

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

所以在这种情况下,你只需要使用渲染

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