下面是一个非常通用的示例,用于创建一个显示验证错误同时保留输入值的表单。在此示例中,假设我们已经设置了 Post 模型:
app/controllers/posts_controller.rb:
class PostsController < ApplicationController
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
if @post.save
flash[:success] = "Post was created!"
redirect_to posts_path
else
flash[:error] = "Post could not be saved!"
# The 'new' template is rendered below, and the fields should
# be pre-filled with what the user already had before
# validation failed, since the @post object is populated via form params
render :new
end
end
private
def post_params
params.require(:post).permit(:title, :body)
end
end
app/views/posts/new.html.erb:
<!-- Lists post errors on template render, if errors exist -->
<% if @post.errors.any? %>
<h3><%= flash[:error] %></h3>
<ul>
<% @post.errors.full_messages.each do |message| %>
<li>
<%= message %>
</li>
<% end %>
<% end %>
<%= form_for @post, html: {multipart: true} |f| %>
<%= f.label :title %>
<%= f.text_field :title, placeholder: "Title goes here" %>
<%= f.label :body %>
<%= f.text_area :body, placeholder: "Some text goes here" %>
<%= f.submit "Save" %>
<% end %>
以上是一个基本设置,它将向用户显示哪些字段未通过验证,同时在呈现模板时保留输入字段值。有大量的表单库可以帮助使您的表单看起来/表现更好 - 这里有两个流行的选项:
还有一个有用的RailsCasts screencast 用于客户端验证。
RailsGuides 有大量关于 ActiveRecord(模型)验证的文档。
希望这会有所帮助!