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("answers")
我得到了“Response”的预期结果。
我想做的是让验证错误消息显示:
“响应答案文本不能为空”。我需要解决什么问题吗?
I've got two models
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
In my nested form if validation fails I get this error displayed on the screen:
"answers answer text can't be blank"
I've customized my attribute names somewhat successfully using rails I18n. It doesn't behave exactly how I would expect though. The yml file below doesn't affect how the attribute name is printed in error_messages_for
en:
activerecord:
models:
survey_response:
answers: "Response"
But if from script/console I try
SurveyResponse.human_attribute_name("answers")
I get the expected result of "Response".
What I'd like to do is have the validation error message say:
"Response answer text can't be blank". Any ideas what I need to fix?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从 Rails 3.2.0 开始,i18n yaml 已更改为
(注意斜杠。)这还允许您在集合本身上定义属性名称,例如
来源:https://github.com/rails/rails/pull/3859
As of Rails 3.2.0, the i18n yaml has changed to
(Note the slash.) This also permits you to define an attribute name on the collection itself, e.g.
Source: https://github.com/rails/rails/pull/3859
试试这个:
我正在使用 Rails 3,这对我有用(我的 i18n 文件有点不同,使用“属性”而不是模型。我不知道这在 2.3 中是否有效)
在此之前,我试图创建一个yml 中的属性名为“answers_answer_text”,但它不起作用。
我希望这能解决您的问题。
Try this:
I am using Rails 3 and this is working for me (my i18n file is a bit different, using "attributes" instead of models. I don't know if this works in 2.3)
Before that I was trying to create a attribute in the yml called "answers_answer_text" but it was not working.
I hope this solves your issue.