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

标签 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

在我的主页/索引中,我呈现了帖子形式的部分内容。
= 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 后,它应该将错误保留在表单的底部。

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

最佳答案

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

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带有你的 Controller 和 Action 的名字

另请检查此 question

关于ruby-on-rails - 从部分重定向回具有部分的同一页面后保持验证错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16095883/

相关文章:

css - 部署到 Heroku 时,Rails 中未显示 FontAwesome 图标

ruby-on-rails - 如何在模块外部调用方法

ruby-on-rails - 为什么 User.last(2) 和 User.first(2) 返回相同的用户?

ruby-on-rails - 在Rails 3.x中按坐标查询距离

jquery - Rails jquery tokeninput 返回 "not a function"

ruby-on-rails - 加速 Rails 5.1/Webpacker 应用程序的部署

ruby-on-rails - 在 Rails 3 和 ActionMailer 中,是否可以使用 TLS over SSL(不是 StartTLS)发送电子邮件?

jquery - 如何正确设置 ajax Button_to 上的路由?

ruby-on-rails - Gitlab CE 不发送电子邮件

ruby-on-rails - 如何在 App Engine 上运行 Ruby on Rails