所以我试图从我的表单中获取错误,这些错误在我的 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/