Re: [问题]关于验证后出错的显示

seairy在论坛里问:
[quote]在models添加validates_xxx方法后,页面的出错信息标题如何更改默认呢?

比如红色框的标题是
1 error prohibited this customer from being saved

还有就是我更改了environment.rb中的ActiveRecord::Errors.default_error_messages,例如::blank => "不能为空",但是错误提示中显示的字段名仍然是英文,例如:“Name 不能为空”,请问“Name”如何更改为我希望的名称呢?[/quote]

我的解决方案是,在app/helpers/application_helper.rb里重写rails的error_messages_for函数:

def error_messages_for(object_name, options = {})
options = options.symbolize_keys
object = instance_variable_get("@#{object_name}")
if object && !object.errors.empty?
content_tag("div",
content_tag(
options[:header_tag] || "h2",
"保存该#{object.class::ALIAS}时发生#{object.errors.count}个错误。"
) +
content_tag("ul", object.errors.collect { |attr, msg| content_tag("li", object.class::COLUMN_ALIASES[attr] + msg) }),
"id" => options[:id] || "errorExplanation", "class" => options[:class] || "errorExplanation"
)
else
""
end
end


请注意这里面的两个ALIAS,一个是object.class::ALIAS,一个是object.class::COLUMN_ALIASES[attr]。就用你的例子来说明这两个alias:

class Customer < ActiveRecord::Base
ALIAS = '客户'
COLUMN_ALIASES = {
'name' => '客户名称',
'address' => '地址'
# some other columns
}

# other codes in this model
end


这样的话,再加上你在environment.rb中设置的ActiveRecord::Errors.default_error_messages,他的报错信息就会是:
[color=red]保存该客户时发生2个错误。
* 客户名称不能为空。
* 地址不能为空。[/color]

今天看到一个很好的i18n/l10n的Ruby库:[url=http://require.errtheblog.com/plugins/browser/gibberish/README]gibberish[/url]。这是一个很干净,很ruby的实现方式,也许用它可以有更好的解决方法。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值