在Rails中error_messages_for为国际化的考虑不是很周全,它显示的是模型的字段名称,这对于用户来说是不友好的。为了解决这个问题,只能改它的源码了----将如下方法,放入
ApplicationHelper
文/陈刚 www.chengang.com.cn 转载请声明出处
def error_messages_for(*params)
#add by glchengang
key_hash = {}
if params.first.is_a?(Hash)
key_hash = params.first
params.delete_at(0)
end
#add end
options = params.last.is_a?(Hash) ? params.pop.symbolize_keys : {}
objects = params.collect {|object_name| instance_variable_get("@#{object_name}") }.compact
count = objects.inject(0) {|sum, object| sum + object.errors.count }
unless count.zero?
html = {}
[:id, :class].each do |key|
if options.include?(key)
value = options[key]
html[key] = value unless value.blank?
else
html[key] = 'errorExplanation'
end
end
# change by glchengang
header_message = "有#{count}个错误"
# header_message = "#{pluralize(count, 'error')} prohibited this #{(options[:object_name] || params.first).to_s.gsub('_', ' ')} from being saved"
#add by glchengang
error_messages = objects.map do |object|
temp = []
object.errors.each do |attr, msg|
temp << content_tag(:li, (key_hash[attr] || attr) + msg)
end
temp
end
#add end
# error_messages = objects.map {|object| object.errors.full_messages.map {|msg| content_tag(:li, msg) } }
content_tag(:div,
content_tag(options[:header_tag] || :h2, header_message) <<
# content_tag(:p, 'There were problems with the following fields:') <<
content_tag(:ul, error_messages),
html
)
else
''
end
end
使用依然兼容老的方式,你也可以传入一个哈希表,把模型字段显示成对应的中文,示例如下:
<%=
h = {'username'=>'用户名', 'password'=>'密码'}
error_messages_for h, :user
%>
另外,还要在environment.rb的最后插入以下代码:
errors = ActiveRecord::Errors.default_error_messages
errors[:taken] = '已经被使用'
errors[:blank] = '不能为空'