我正在使用带有设计的rails 3.
我有一个包含字段的用户表:email,password,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,:length =&gt; {:minimum =&gt; 1,:maximum =&gt; 100} 验证:lname,:length =&gt; {:minimum =&gt; 1,:maximum =&gt; 100}
我可以使用message属性自定义这些字段。怎么样的电子邮件和密码似乎被构建到设计中?如何自定义这些错误消息?
由于
答案 0 :(得分: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他们
答案 1 :(得分: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