2012-02-22 67 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