0

我正在使用Ruby on Rails 3.1,我想知道如何正確處理與「資源資源」相關的國際化。也就是說,...使用i18n gem與「資源資源」的問題

...我config/routes.rb文件我有:

resources :users do 
    resource :account 
end 

...我app/models/users/account.rb文件我有:

class Users::Account < ActiveRecord::Base 
    validates :firstname, 
    :presence => true 
    ... 
end 

...我config/locales/models/user/account/en.yml文件我有:

en: 

    activerecord: 
    errors: 
     messages: 
     presence: "custom presence message - english" 

...在我的config/locales/models/user/account/it.yml文件我有:

it: 

    activerecord: 
    errors: 
     messages: 
     presence: "custom presence message - italian" 

上面的代碼中不前面顯示結束「custom presence message(它仍然顯示默認的回報率存在消息:can not be blank)。此外,如果在我的app/models/users/account.rb文件我用:

class Users::Account < ActiveRecord::Base 
    validates :firstname, 
    :presence => { :message => t(:presence) } # Here I try to use the i18n helper method 
    ... 
end 

我得到以下錯誤:

NoMethodError (undefined method `t' for #<Class:0x000001075bbc80>) 

爲什麼我得到的NoMethodError

問題涉及我在目錄我的區域設置文件中如何組織?在這個時候我的文件系統(如official RoR guide說明)是:

config/locales/defaults/en.yml 
config/locales/defaults/it.yml 
config/locales/models/user/en.yml 
config/locales/models/user/it.yml 
config/locales/models/user/account/en.yml 
config/locales/models/user/account/it.yml 

在幾句話,我想展示我的「custom presence message」僅在驗證了「資源的資源」之類的Users::Account我該怎麼做?


我也試圖說明下面的代碼在config/locales/models/user/account/en.yml文件

en: 

    activerecord: 
    errors: 
     models: 
     user: 
      account: 
      attributes: 
       firstname: 
       blank: "custom presence message - english" 

,但它不工作。反正下面的作品,但我需要爲不同的屬性不同的翻譯(當我試着在上面的代碼示例來說明):

en: 

    activerecord: 
    errors: 
     messages: 
     blank: "custom presence message - english" 
+0

5.1.1錯誤消息的作用域 - 請仔細閱讀非常該條你提到過的同一個指南 – 2012-01-06 15:17:49

+0

@PiotrMąsior - 我讀了那部分(它也提到模型繼承,在我的情況下,我沒有使用),但是我找不到關於「資源資源」的信息以及如何組織相關的語言環境文件。此外,我不知道爲什麼我會得到'NoMethodError'。 – user12882 2012-01-06 15:24:57

+0

如果你在「generate_message」定義裏面找到ActiveModel gem lib/active_model/errors.rb第297行,你會發現類似於class.model_name.i18n_key被調用....並且它爲命名空間模型生成了如下內容:= >:「用戶/帳戶」 – 2012-01-06 16:05:38

回答

2

OK,由於這樣的:去年https://github.com/rails/rails/issues/1402評論嵌套模型查找被刪除

所以儘量可能像

activerecord: 
    errors: 
     models: 
     users: 
      account: 
      attributes: 
       first_name: 
       blank: "You should fill up first name field to complete that" 

和改變內部:消息散列

I18n.t(:"activerecord.errors.models.users.account.attributes.first_name.blank") 

,並儘量避免嵌套模型;-)

更新:

經過一番調試運行,這將工作:

activerecord: 
    errors: 
     models: 
     "users/account": 
      attributes: 
       first_name: 
       blank: "You should fill up first name field to complete that"