【问题标题】:Rails Application Form ValidationRails 申请表验证
【发布时间】:2015-09-28 17:16:06
【问题描述】:

我正在开发一个 Rails 项目,我想对其进行表单验证。当客户端和/或服务器端验证失败时,我想使用用户之前输入的值自动填充表单字段并指向那些不正确的字段。

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

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

【问题讨论】:

    标签: ruby-on-rails forms validation


    【解决方案1】:

    下面是一个非常通用的示例,用于创建一个显示验证错误同时保留输入值的表单。在此示例中,假设我们已经设置了 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(模型)验证的文档。

    希望这会有所帮助!

    【讨论】:

    • 谢谢,我正在阅读所有这些内容。但是现在好像一切都搞砸了,我无法连接所有这些东西。就像如何开始编码一样。您能否告诉我实施和理解更多内容的步骤。
    猜你喜欢
    • 2014-11-29
    • 1970-01-01
    • 2020-08-27
    • 2011-04-02
    • 2020-06-24
    • 2016-10-29
    • 2012-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多