从部分重定向回具有部分的同一页面后保持验证错误

jam*_*mby 4 ruby-on-rails

所以我试图从我的表单中获取错误,这些错误在我的 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
Run Code Online (Sandbox Code Playgroud)

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

= 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
Run Code Online (Sandbox Code Playgroud)

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

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

ole*_*ole 5

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

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
Run Code Online (Sandbox Code Playgroud)

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

也检查这个问题