Rails 上面 Error Message 中文化

Rails 有一點設計的不夠完善
就是 i18n 的問題
當然這個問題可以用 gettext 去解決
不過 , 如果有更簡單的方式 , 也是不錯的
到目前為止
Model 裡面的 Validate Error 目前是官方無解的
所以我就從 Rails Wiki 裡面找出了不錯的解法
第一個連結
第二個連結

老師有說過
好的設計帶你上天堂, 不好的設計帶你住套房
Rails 以 Ruby 當作中心語言雖然沒有到上天堂的程度
但是 Ruby 的 Open Class 的特性
卻讓這個解法不需要動用到Rails目錄裡面去修改 Source Code
可說是相當有趣的解法

寫下列的程式在 你的 app 目錄下面

module ActiveRecord
class Errors
begin
@@default_error_messages.update( {
:inclusion => “ist nicht in Liste g羹ltiger Optionen enthalten”,
:exclusion => “ist reserviert”,
:invalid => “ist ung羹ltig”,
:confirmation => “entspricht nicht der Best瓣tigung”,
:accepted => “muss akzeptiert werden”,
:empty => “不能是空的”,
:blank => “darf nicht leer sein”,
:too_long => “ist zu lang (h繹chstens %d Zeichen)”,
:too_short => “ist zu kurz (mindestens %d Zeichen)”,
:wrong_length => “hat eine falsche L瓣nge (es sollten %d Zeichen
sein)”,
:taken => “ist schon vergeben”,
:not_a_number => “不能是空的”,
})
end
end
end

module ActionView #nodoc
module Helpers
module ActiveRecordHelper
def error_messages_for(object_name, options = {})
options = options.symbolize_keys
object = instance_variable_get(”@#{object_name}”)
unless object.errors.empty?
content_tag(”div”,
content_tag(
options[:header_tag] || “h2″,
“一共有 #{pluralize(object.errors.count, “error”)} 問題 “
) +
content_tag(”p”, “請更正:”) +
content_tag(”ul”, object.errors.full_messages.collect { |msg| content_tag(”li”, msg) }),

“id” => options[:id] || “errorExplanation”, “class” => options[:class] || “errorExplanation”
)
end
end
end
end
end

然後,
config/enviorment.rb 加入

require “#{RAILS_ROOT}/app/你的filename”

成品如下圖


 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值