2015-07-10 46 views
0

我正在研究一个Rails项目,并且我想对它实施表单验证。当客户端和/或服务器端验证失败时,我想用以前用户输入的值自动填充表单字段,并指出那些不正确的字段。Rails申请表验证

我想要实现的是创建一个Model ValidForm并使用验证进行客户端验证。我应该如何继续自动填充表单字段并跟踪导致表单验证失败的原因。同样在这种形式中,我必须上传一个需要在服务器端进行验证的文件。

我是Rails的初学者,所以请给我指出正确的方向来实现这一点。

回答

0

下面是一个非常通用的例子,用于创建一个可以显示验证错误的表单,同时保留输入值。在这个例子中,假设我们有一个Post模型已经建立:

应用程序/控制器/ 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 

应用程序/视图/职位/ 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(模型)验证方面有很多文档。

希望这有助于!

+0

谢谢,我正在阅读所有这些。但现在就好像一切都搞砸了,我无法连接所有这些东西。 像如何开始编码它。你能否告诉我要遵循的步骤来实现和理解更多。 –