2015-07-10 66 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

謝謝,我正在閱讀所有這些。但現在就好像一切都搞砸了,我無法連接所有這些東西。 像如何開始編碼它。你能否告訴我要遵循的步驟來實現和理解更多。 –