2012-03-04 78 views
3

我在Ruby On Rails(3.1)上運行應用程序,需要處理翻譯成各種語言。我有我的控制器使用文本的國際化feautures妥善處理,但對於驗證模型中,尤其是這樣的:如何翻譯模型中驗證引發的(I18N)錯誤文本(Ruby On Rails)

validate :valid_quantities? 

def valid_quantities? 
    if self.quantity*self.unitprice < 1.00 
    errors.add("The transaction value", "is < 1.00") 
    return false 
end 

我將如何編寫這爲其他語言的支持?
另外,如何處理數字的格式?我無法調用ActionView助手和用戶,例如number_to_currency

回答

1

好吧,我做了部分進展,看起來像以下工作:

更改模型驗證,以

errors.add(" ",I18n.t(:valid_quantities,:amount=>1.00)) 

代碼輸入翻譯成de.yml

de: 
    valid_quantities: "Der Mindestwert einer Order ist %{amount}" 

但我仍在尋找一種方法來正確格式化該編號(英文爲1.00,1,00 fo德語)。

3

有關標準驗證,請參閱http://guides.rubyonrails.org/i18n.html#error-message-scopes。爲了您的自定義驗證,爲什麼不使用I18n.t?

errors.add(:transaction_value, I18n.t("errors.attributes.transaction_value.below_1")) 
+0

不能似乎得到它的工作,我添加它,以及增加了翻譯成de.yml如下 錯誤: 屬性: transaction_value: below_1:明鏡Transaktionswert北京時間克萊納1.00 但我仍然得到錯誤信息: 交易值翻譯丟失:de.errors .attributes.transaction_valu e.below_1 – KKK 2012-03-04 13:23:24

8

我這樣做:

total_price = self.quantity*self.unitprice 
errors.add(:transaction_value, :transaction_undervalued, { value: total_price }) 

恕我直言,你將能更好地使用像:transaction_undervalued一個簡單的關鍵字,這樣的I18n看幾個命名空間,根據rails guides - i18n - error message scopes

activerecord.errors.models.[model_name].attributes.transaction_undervalued 
activerecord.errors.models.[model_name] 
activerecord.errors.messages 
errors.attributes.transaction_undervalued 
errors.messages 

*替換[模型名稱]與模型使用此驗證

對於語言環境的一部分,這是/config/locales/en.yml一個例子

en: 
    errors: &errors 
    messages: 
     transaction_undervalued: "The transaction value is %{value}. That is < 1.00"