2010-06-17 34 views
15

我有兩個型號的Rails的I18n accepts_nested_attributes_for和error_messages_for

class SurveyResponse 
    has_many :answers, :class_name => SurveyResponseAnswer.name 
    accepts_nested_attributes_for :answers 
end 

class SurveyResponseAnswer 
    belongs_to :survey_response 
    validates_presence_of :answer_text 
end 

在我的嵌套形式,如果驗證失敗,我得到的屏幕上顯示此錯誤:

「的答案回答的文字不能爲空「

我已經使用rails I18n有點成功地定製了我的屬性名稱。它並不像我期望的那樣行事。下面的YML文件不影響屬性的名稱是如何印在error_messages_for

en: 
    activerecord: 
    models: 
     survey_response: 
     answers: "Response" 

但是,如果從腳本/控制檯我嘗試
SurveyResponse.human_attribute_name(「答案」)

我得到預期的結果的「迴應」。

我希望做的是有驗證錯誤消息說:

「響應答覆文件不能爲空」。任何想法我需要修復?

回答

13

試試這個:

en: 
    activerecord: 
    models: 
     survey_response: 
     answers: 
      answer_text: "Response" 

我使用Rails 3中,這是爲我工作(我的i18n文件是有點不一樣,使用「屬性」,而不是模型,我不知道這作品2.3)

en: 
    activerecord: 
    attributes: 
     survey_response: 
     answers: 
      answer_text: "Response" 

在此之前,我試圖創建一個名爲「answers_answer_text」的YML一個屬性,但它不工作。

我希望這可以解決您的問題。

+0

3.1中運行良好。謝謝! – 2011-10-14 08:39:18

+3

實際上,不太好:'[DEPRECATION WARNING]不再支持「activerecord.attributes.survey_response」下的嵌套I18n名稱空間查找。但是通過[本次討論](https://github.com/rails/rails/issues/1869),似乎還沒有完全正常工作的未被棄用的替代方案。 – 2011-10-14 09:31:41

52

鐵軌3.2.0的,國際化的YAML已更改爲

en: 
    activerecord: 
    attributes: 
     survey_response: 
     foo: "Foo" 
     survey_response/answers: 
     answer_text: "Response" 

(注意斜線。)這還允許您在集合本身,例如定義屬性名稱

en: 
    activerecord: 
    attributes: 
     survey_response: 
     foo: "Foo" 
     answers: "Ripostes" 
     survey_response/answers: 
     answer_text: "Response" 

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

+0

非常感謝。我可以證實這在Rails 3.2.8中適用於我,其他方面都沒有。花了我一個多小時的搜索! – brad 2012-08-22 03:21:07

+2

謝謝!它適用於rails 4.0 :) – 2013-10-17 20:08:34

+2

它也適用於Rails 4.1。它應該被接受= P – 2014-06-12 22:42:30