在提交表单之后,如果模型validate不通过,会往@user.errors里加入失败信息,@user.save失败后重新渲染『new』时会展示错误提示。
展示错误信息的模板:
app/views/shared/_error_messages.html.erb
<% if @user.errors.any? %>
<div id="error_explanation">
<div class="alert alert-danger">
The form contain <%= pluralize(@user.errors.count, "error") %> :(
</div>
<ul>
<% @user.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
# 注:
# 模板片段filename以下划线开头,
# 通过 <%= render 'shared/error_messages' %> 插入到 app/views/users/new.html.erb 中
activemodel中的错误信息处理:
/Users/cbd/.rvm/gems/ruby-2.3.0/gems/activemodel-4.2.6/lib/active_model/errors.rb
def full_messages
map { |attribute, message| full_message(attribute, message) }
end
# Returns all the full error messages for a given attribute in an array.
#
# class Person
# validates_presence_of :name, :email
# validates_length_of :name, in: 5..30
# end
#
# person = Person.create()
# person.errors.full_messages_for(:name)
# # => ["Name is too short (minimum is 5 characters)", "Name can't be blank"]
# Returns a full message for a given attribute.
#
# person.errors.full_message(:name, 'is invalid') # => "Name is invalid"
def full_message(attribute, message)
return message if attribute == :base
attr_name = attribute.to_s.tr('.', '_').humanize
attr_name = @base.class.human_attribute_name(attribute, default: attr_name)
I18n.t(:"errors.format", {
default: "%{attribute} %{message}",
attribute: attr_name,
message: message
})
end
app/models/user.rb
## 密码验证
validates :password,length: {minimum: 6, message: "密码最少六位"}
# 这里的message就是长度验证失败时的错误信息
# 效果如上图
关于『Name,Email,Password』字样如何自定义为合适的中文,这里就要用到国际化的gem了——rails-i18n。
配置 config/application.rb
# 国际化
# # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
config.i18n.default_locale = :zh
新建文件 config/locales/zh.yml
zh:
activerecord:
attributes:
user:
name: "帐号"
email: "邮箱"
password: "密码"
password_confirmation: "重复密码"
errors:
models:
user:
attributes:
name:
blank: "不得为空"
email:
blank: "不得为空"
password:
blank: "不得为空"