2012-03-05 30 views
2

我在寫一些if/elsif語句來顯示錯誤消息。當我將用戶名留空並正確填寫其他字段時,它仍會轉到else語句並顯示「所有字段必須完成」。有人能指出我的邏輯/語法錯誤嗎?寫入form_for錯誤消息的條件

<% if @user.errors.any? %> 
    <div id="error_explanation" class="round"> 

    <% if @user[:name].nil? and @user[:email].not.nil? and @user[:password].not.nil? and @user[:password_digest].not.nil? %>  
     <h2>Please enter a valid username. </h2> 


    <% else %>  <!--If any field is left blank --> 
     <h2>All fields must be completed. </h2> 

    <% end %> 
</div> 
<% end %> 

讓我知道你是否需要別的東西。

回答

2

我認爲railscasts有驗證http://railscasts.com/episodes/211-validations-in-rails-3

檢查出來大發作,你目前的做法是一定要在將來一些麻煩,你需要檢查驗證了很多。

+0

感謝您的鏈接! – Huy 2012-03-05 17:05:37

+0

我在user.rb中爲我的用戶創建了我的驗證測試。我上面的代碼只是爲了讓訪問者在網站上顯示錯誤消息。視頻方法比我目前的方法更有效嗎? – Huy 2012-03-05 19:46:19

+0

跟着視頻,它的作品。再次感謝你,艾傑! – Huy 2012-03-05 19:58:45

0

試一下這個

<% if @user[:name].nil? and [email protected][:email].nil? and [email protected][:password].nil? and [email protected][:password_digest].nil? %> 
+0

我試過了,但它仍然顯示else消息。 '<如果@user [:name] .nil? &&!@user [:email] .nil? &&!@user [:password] .nil? &&!@user [:password_digest] .nil? %>' – Huy 2012-03-05 07:55:21

+0

這是調試信息: 名稱:「」 電子郵件:[email protected] 密碼:foobar的 password_confirmation:foobar的 – Huy 2012-03-05 07:56:54

+0

您可以登錄該領域的條件語句,並檢查自己是否被設置爲你正在考慮 – gt5050 2012-03-05 08:03:13