32

我有特殊的驗證屬性,我使用message子句來顯示一個特殊的消息,只是爲了驗證。這裏有一個例子:Ruby on Rails i18n - 想翻譯模型中的自定義消息

validates :email, presence: true, length: { maximum: 60 }, 
       format:  { with: valid_email_regex, message: "is not a valid email address format." }, 
       uniqueness: { case_sensitive: false } 

我想翻譯這裏的消息,但我不知道該怎麼做。

我看過例子,他們鍵入類似這樣的消息:t(「some_value_here」)。我不確定這個稱號。我嘗試了這樣的消息:t(:bad_email)。我在我的yaml文件中做了以下事情,只是爲了嘗試一些。

activemodel: 
    errors: 
    bad_email: "is not a valid email address format." 

當我試圖訪問我的Rails應用程序,我得到了以下錯誤:

ActionView::Template::Error (undefined method `t' for #<Class:0x007fefc1b709e0>) 

我也試過這在我的YAML文件:

activemodel: 
    errors: 
    user: 
     bad_email: "is not a valid email address format." 

我一直在研究這一關並整天。我能找到的就是替換內置的錯誤散列,如空白或空白。有沒有辦法讓我有自定義錯誤哈希並替換它們在模型中?在這一點上,我不能讓編碼工作。我希望問題是我如何設置yaml文件。我已經看到了如何設置的不同版本。我不確定是否應該將其置於activemodel或activerecord之下。我假設activemodel,因爲這是我想翻譯的自定義消息。

任何幫助,將不勝感激。這是我在開始第一次翻譯應用程序之前需要弄清楚的最後一部分。

UPDATE 2013年7月29日下午7:30 CDT

bgates給了我一個很好的開始與如何設置我的模型文件,以對YAML文件接收自定義消息。然而,我最終不得不在我的yaml文件中爲自定義消息找到以下設置。

activerecord: 
    errors: 
    models: 
     user: 
     attributes: 
      bio: 
      no_links: "cannot contain email addresses or website links (URLs)." 
      email: 
      bad_email: "is not a valid email address format." 
      username: 
      bad_username: "can only contain numbers and letters. No special characters or spaces." 

回答

63

使用符號的消息:

validates :email, presence: true, length: { maximum: 60 }, 
      format:  { with: valid_email_regex, message: :bad_email }, 
      uniqueness: { case_sensitive: false } 

然後在YAML文件

[lang]: 
    activerecord: 
    errors: 
     messages: 
     bad_email: "just ain't right" 

如果有這種模式的具體翻譯,它將覆蓋上述一般一個:

[lang]: 
    activerecord: 
    errors: 
     models: 
     model_name: # or namespace/model_name 
      attributes: 
      email: 
       bad_email: "model-specific message for invalid email" 

如果您編寫自定義驗證,add_error(:email, :bad_email)將執行上面的查找,但errors[:email] << :bad_email不會。

+0

設置我的模型和YAML文件。我找不到activerecord.errors.models.user.attributes.email.bad_email的翻譯。我在我的描述中將我在yaml文件中所做的更改。它運作良好。非常感謝幫助我開始。 –

+0

我不得不使用'activemodel'而不是'activerecord'作爲我的頂級密鑰。有關更多詳細信息,請參見錯誤[來源](https://github.com/rails/rails/blob/ccbc98e37dcc11ad5150b93dcee8008bc94aa83a/activemodel/lib/active_model/errors.rb#L465-L472)。 – Nick

+0

好戲,謝謝 –

20

我剛剛走過所有這些,發現rails guides for custom validators太硬編碼...即使這不是你問的東西,但Q標題完全適合(這就是爲什麼我讀這篇文章爲我的問題)。

自定義驗證與國際化的消息:

validate :something_custom?, if: :some_trigger_condition 

def something_custom? 
    if some_error_condition 
    errors.add(:some_field_key, :some_custom_msg) 
    end 
end 

# en.yml 
activerecord: 
    errors: 
    models: 
     some_model: 
     some_custom_msg: "This is i18n controlled. yay!"