Rails I18n accepted_nested_attributes_for和error_messages_for

Mik*_*ike 17 ruby-on-rails internationalization 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
Run Code Online (Sandbox Code Playgroud)

在我的嵌套表单中,如果验证失败,我会在屏幕上显示此错误:

"答案答案文字不能为空"

我使用rails I18n成功地定制了我的属性名称.它的行为并不像我期望的那样.下面的yml文件不会影响error_messages_for中打印属性名称的方式

en: 
  activerecord:
    models:
      survey_response:
        answers: "Response"
Run Code Online (Sandbox Code Playgroud)

但是如果从脚本/控制台我尝试
SurveyResponse.human_attribute_name("答案")

我得到了"响应"的预期结果.

我想要做的是验证错误消息说:

"响应答案文本不能为空".我需要解决的任何想法?

小智 55

从Rails 3.2.0开始,i18n yaml已经改为

en: 
  activerecord:
    attributes:
      survey_response:
        foo: "Foo"
      survey_response/answers:
        answer_text: "Response"
Run Code Online (Sandbox Code Playgroud)

(注意斜杠.)这也允许您在集合本身上定义属性名称,例如

en: 
  activerecord:
    attributes:
      survey_response:
        foo: "Foo"
        answers: "Ripostes"
      survey_response/answers:
        answer_text: "Response"
Run Code Online (Sandbox Code Playgroud)

资料来源:https://github.com/rails/rails/pull/3859

  • 谢谢!它适用于rails 4.0 :) (2认同)
  • 它也适用于Rails 4.1.它应该被接受= P. (2认同)

小智 14

试试这个:

en: 
  activerecord:
    models:
      survey_response:
        answers:
          answer_text: "Response"
Run Code Online (Sandbox Code Playgroud)

我正在使用Rails 3,这对我有用(我的i18n文件有点不同,使用"属性"而不是模型.我不知道这是否适用于2.3)

en: 
  activerecord:
    attributes:
      survey_response:
        answers:
          answer_text: "Response"
Run Code Online (Sandbox Code Playgroud)

在此之前,我试图在yml中创建一个名为"answers_answer_text"的属性,但它无法正常工作.

我希望这能解决你的问题.

  • 实际上,不太好:'[DEPRECATION WARNING]不再支持"activerecord.attributes.survey_response"下的嵌套I18n命名空间查找.但是,通过[此讨论](https://github.com/rails/rails/issues/1869),似乎还没有一个完全正常的非弃用替代方案. (3认同)