2017-03-17 77 views
0

我在我的Rails項目中爲我的帖子添加驗證。一切都適用於編輯,但在新窗體上,警告div已經出現在表單實際上被引用之前。我如何解決它的方式,只有在驗證返回false時,div纔會出現在表單提交中。 THX)在提交之前對新表單進行Rails驗證

posts_controller

def new 
    @post = Post.new 
end 

def create 
    post = Post.new(post_params) 
    if post.valid? 
     post.save 
     redirect_to post_path(post.id), success: "..." 
    else 
     @post = post 
     render 'new' 
    end 
end 

new.html.erb

<h1>Nouvel article</h1> 

<% if @post.invalid? %> 
    <div class="alert alert-danger"> 
    <% @post.errors.full_messages.each do |message| %> 
     <%= message %><br> 
    <% end %> 
    </div> 
<% end %> 

<%= form_for @post do |f| %> 
    <div class="form-group"> 
    <label>Titre de l'article</label> 
    <%= f.text_field :name, class: "form-control" %><br /> 
    <label>Contenu de l'article</label> 
    <%= f.text_area :content, class: "form-control" %> 
    </div> 
    <div class="form-group"> 
    <button type="submit" class="btn btn-success">...</button> 
    </div> 
<% end %> 

回答

0

您可以添加changed?檢查您的模板:

<% if @post.changed? && @post.invalid? %> 
    <div class="alert alert-danger"> 
    <% @post.errors.full_messages.each do |message| %> 
     <%= message %><br> 
    <% end %> 
    </div> 
<% end %> 
+0

這部分工作,因爲我沒有看到紅色警戒div時,我到達窗體中,但我沒有看到它,當我現在如果我不'通過驗證例如留下姓名blanck)。 – frogtube

+0

對,原始版本在所有情況下都不正確。你可以嘗試新版本嗎?希望新人能正確工作。 –

+0

回到最初,當我到達頁面時,紅色div在那裏。 – frogtube

0

如果使用#invalid?這種方法在分配任何屬性之前調用驗證。您需要替換如果@[email protected]與如果@post.errors.any?

相關問題