Rails 上面 Error Message 中文化

来源:互联网 发布:知托付 编辑:程序博客网 时间:2024/05/21 19:16
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”

成品如下圖


 
原创粉丝点击