2010-06-17 37 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