【问题标题】:Rails I18n accepts_nested_attributes_for and error_messages_forRails I18n 接受_nested_attributes_for 和 error_messages_for
【发布时间】:2011-03-04 18:59:05
【问题描述】:

我有两个模型

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("答案")

我得到了“响应”的预期结果。

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

“响应答案文本不能为空”。有什么想法我需要解决的吗?

【问题讨论】:

    标签: ruby-on-rails internationalization error-messages-for


    【解决方案1】:

    从 Rails 3.2.0 开始,i18n 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

    【讨论】:

    • 非常感谢。我可以确认这在 Rails 3.2.8 中对我有用,而没有其他方法。花了我一个多小时的时间搜索!
    • 这正是我想要的。 :)
    • 我只是想为集合定义一个属性名称(例如survey_response.answers: Ripostes),但无法让它在 Rails 5.0.1 上运行。像您提到的那样指定特定字段(survey_response/answers.answer_text),但我无法让它识别集合后备。
    • @stephen.hanson 你有想过那个吗?同样的问题,尝试在nested_attributes 表单上定义错误消息的模型名称
    【解决方案2】:

    试试这个:

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

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

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

    在此之前,我试图在 yml 中创建一个名为“answers_answer_text”的属性,但它不起作用。

    希望这能解决您的问题。

    【讨论】:

    • 实际上,不太好:'[DEPRECATION WARNING] 不再支持“activerecord.attributes.survey_response”下的嵌套 I18n 命名空间查找'。但是通过this discussion,似乎还没有一个完全有效的非弃用替代方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    相关资源
    最近更新 更多