2012-02-13 70 views
7

任何人都有一些提示,如何在Rails中翻譯模型關聯?翻譯Rails模型關聯 - 不工作

例如:我有一個人模型,它可以有很多電話。但是,一個人需要至少有一個電話。我無法翻譯該驗證。我能做的最好的是這樣的:

validates_presence_of :phones, :message => "At least one phone is required." 

而且我YAML,我換成這行省略%{attribute}

format: ! '%{message}' 

這種方式只顯示我的消息,我也避免了非翻譯的字段名稱被顯示。

這使我很頭痛,因爲有些寶石根本不允許我通過:message => "something describing the error",所以我想通過我的YAML配置所有的錯誤信息。

此外,有些模型可以翻譯他們的屬性,而有些模型我不能。例如:

activerecord: 
    attributes: 
    additional_info: 
     account_manager: "Manager" 

This works。我可以在我的表格上看到「經理」。但是,當該字段出現錯誤時,Rails將顯示爲"Additional info account manager can't be blank"

我嘗試這樣做:

activerecord:   
    errors: 
    models: 
     additional_info: 
     attributes: 
      account_manager: "Manager" 

,但沒有運氣。

我確實閱讀過文檔,但沒有理解它爲什麼會發生。

回答

9

Rails 3.2改變了這種行爲。我之前發佈的方式已被棄用。

現在,爲了翻譯關聯,需要添加一個斜槓(而不是嵌套所有內容)。因此,而不是這樣的:

activerecord: 
     attributes: 
     person: 
      additional_info: 
      account_manager: "Manager" 

正確的,現在是:

activerecord: 
     attributes: 
     person: 
      additional_info/account_manager: "Manager" 

而且,我想通了,has_many協會正在從翻譯不同。如果你想翻譯的,下面的例子可能會有幫助:

activerecord: 
     attributes: 
     emails: 
      address: "E-mail field" 

取而代之的是型號名稱,就像我上面那樣,你需要通過協會的名稱,在這種情況下emails

檢查此評論和更多信息拉入請求:

https://github.com/rails/rails/commit/c19bd4f88ea5cf56b2bc8ac0b97f59c5c89dbff7#commitcomment-619858

https://github.com/rails/rails/pull/3859

+0

我想這樣的事情,但不是運氣的項目上如何找到它,感謝的確切位置,而不是運氣!非常感謝 – Alexis 2014-06-15 07:47:38

7

下面是Rails的有效鍵路徑4。1:

# Basic Attribute on Model 
activerecord: 
    attributes: 
    #{model_class.model_name.i18n_key}: 
     #{attribute_name}: 
     "Localized Value" 

# Attribute on Nested Model 
activerecord: 
    attributes: 
    #{model_class.model_name.i18n_key}/#{association_name}: 
     #{attribute_name}: 
     "Localized Value" 
    #{association_name}: 
     #{attribute_name}: 
     "Fallback Localized Value" 

因此,鑑於這種模式(其中有:personi18n_key):

class Person 
    has_many :friends 
end 

你會擁有這些場所的定義:

activerecord: 
    attributes: 
    person: 
     first_name: 
     "My Name" 
    person/friends: 
     first_name: 
     "My Friend's Name" 
    friends: 
     first_name: 
     "A Friend's Name" 

如果你的模型是一個命名空間,如:

class MyApp::Person 
    has_many :friends 
end 

i18n_key成爲:my_app/person和你/鍵開始穿出來:

activerecord: 
    attributes: 
    my_app/person: 
     first_name: 
     "My Name" 
    my_app/person/friends: 
     first_name: 
     "My Friend's Name" 
    friends: 
     first_name: 
     "A Friend's Name"