2011-01-25 44 views
3

這一直困擾着我一段時間。所有模型都會出現此問題,但我將使用其中的一個測驗作爲示例。errors.full_messages:屬性名稱出現兩次

測驗具有以下驗證:

validates_presence_of :size, :style 

我使用的I18n,和我有以下我的翻譯文件中設置:(這些只是標準的錯誤消息,但我將他們我en.yml,這樣很容易看到的結構,如果我想重寫它們對任何特定型號)

activerecord: 
    errors: 
    messages: 
     inclusion: "{{attribute}} is not included in the list" 
     invalid: "{{attribute}} is invalid" 
     empty: "{{attribute}} can't be empty" 
     blank: "{{attribute}} can't be blank" 
     record_invalid: "Validation failed: {{errors}}" 

問題是這樣的:如果我做一個新的測驗,這將無法通過驗證,再看看在quiz.errors.full_messages中,每個錯誤消息都有屬性,然後是完整的消息E:

>> quiz = Quiz.create 
=> <unsaved quiz object> 
>> quiz.errors.full_messages 
=> ["Size Size can't be blank", "Style Style can't be blank"] 

我不明白爲什麼該消息是,例如,"Size Size can't be blank"而不是"Size can't be blank"

任何想法嗎?

+0

有你爲什麼需要添加`什麼特別的原因{{屬性}}`在每個驗證消息的?通常情況下,那裏的條目將只包含錯誤消息,例如「未包含在列表中」。該屬性將根據您的語言環境文件中的`activerecord.errors.full_messages.format`自動添加,默認爲``%{attribute}%{message}「` – sikachu 2011-01-25 11:31:41

+0

Hi Sikachu。這就是他們如何在供應商的軌道 - 我只是將該文件的內容複製到我的en.yml文件(註釋掉),然後根據需要取消註釋和修改。 – 2011-01-27 09:23:26

回答

8

有也應該是:

en: 
    errors: 
    # The default format to use in full error messages. 
    format: "%{attribute} %{message}" 

和你其他的翻譯不應該包括%{attribute}了。 爲了確保你得到所有正確使用en.yml在Rails版本, 它位於:lib/ruby/gems/1.8/gems/activemodel-3.0.3/lib/active_model/locale/en.yml

4

我想通了這一點,我想我會回答它自己的情況下,任何人都有這個問題:我不得不這樣修改我的翻譯的ActiveRecord的部分文件:

activerecord: 
    errors: 
    full_messages: 
     format: "{{message}}"  
    #define standard error messages, which we can overide on per model/per attribute basis further down 
    messages: 
     inclusion: "{{attribute}} is not included in the list" 
     exclusion: "{{attribute}} is reserved" 

的問題是,例如,activerecord.errors.full_messages.format密鑰被設置(在vendor/rails/activerecord/lib/active_record/locale/en.yml)爲「{{attribute}} {{message}}」,並且消息依次被設置爲「{{attribute}}不能爲空」。所以full_message出現爲「{{attribute}} {{attribute}}不能爲空」。將它改爲「{{message}}」解決了這個問題。