2012-02-22 139 views
1

我正在使用rails 3和devise。設計,自定義錯誤消息?

我有一個域用戶表:電子郵件,密碼,FNAME,LNAME

我目前在我看來輸出錯誤如下:

<% if @user.errors.any? %> 
    <div id="error_explanation" class="error"> 
    <h2>Hold on!</h2> 
     <ul> 
      <% @user.errors.full_messages.each do |msg| %> 
       <li><%= msg %></li> 
      <% end %> 
     </ul> 
    </div> 
<% end %> 

問題是這樣呈現爲:

Email The User's Email cannot be blank 
Password The User's Password cannot be blank 
Fname The User's Fname is too short (minimum 1 characters) 
Lname The User's Lname is too short (minimum 1 characters) 

如何讓字段名不會首先出現在每個錯誤中?

以我的用戶模型我有:

驗證:FNAME,:長度=> {:最小=> 1,:最大=> 100} 驗證:L-NAME,:長度=> {:最小=> 1,:maximum => 100}

我可以使用消息屬性自定義這些字段。似乎內置於設計中的電子郵件和密碼怎麼樣?我如何定製這些錯誤消息?

感謝

回答

2

http://ar.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html

validates_presence_of(*attr_names) 

Configuration options: 
    message - A custom error message (default is: "can‘t be blank"). 

至於內置的名字的定製,這個線程可以幫助

Rails3: Devise internationalization does not localize "Password confirmation" and others

(擴大)

activerecord: 
    attributes: 
     user: 
     email: "your_way_of_email" 
      password: "your_way_of_password" 
      password_confirmation: "your_way_of_password_confirmation" 

Rails會然後humanize他們

+0

謝謝,對於名稱定製,問題是我的標籤已關閉... – AnApprentice 2012-02-22 01:37:10

0

使用each_key檢索領域,每個領域的導航誤差。

<% if @user.errors.any? %> 
    <div id="error_explanation" class="error"> 
    <h2>Hold on!</h2> 
     <ul> 
      <% @user.errors.each_key do |attr| %> 
       <% @user.errors[attr].each do |msg| %> 
        <% next if msg.nil? %> 

        <li><%= msg %></li> 
       <% end %> 
      <% end %> 
     </ul> 
    </div> 
<% end %> 

查看full_messages來源: http://ar.rubyonrails.org/classes/ActiveRecord/Errors.html#M000311

+0

這只是顯示電子郵件 密碼 FNAME LNAME ......我想對方:) – AnApprentice 2012-02-22 01:26:48

+0

對不起,我固定它:) – fjyaniez 2012-02-22 01:35:51