如何定制轨ActiveRecord的验证错误消息显示属性值 [英] how to customize rails activerecord validation error message to show attribute value
本文介绍了如何定制轨ActiveRecord的验证错误消息显示属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当用户尝试创建一个记录已存在,我想告诉像一个错误信息的名称:
When a user tries to create a record with a name that already exists, I want to show an error message like:
名称有些名已经采取了
我一直在努力做的:
validates_uniqueness_of :name, :message => "#{name} has already been taken"
但这输出表名称,而不是名称属性的值
but this outputs the table name instead of the value of the name attribute
推荐答案
2的事情:
- 验证信息使用滑轨的I18n风格插值,这是
%{值}
- 在最关键的是
值
,而不是名称
,因为在国际化的背景下,你真的不关心关于模型的其余部分。
- The validation messages use the Rails I18n style interpolation, which is
%{value}
- The key is
value
rather thanname
, because in the context of internationalization, you don't really care about the rest of the model.
所以,你的code应该是:
So your code should be:
validates_uniqueness_of :name, :message => '%{value} has already been taken'
这篇关于如何定制轨ActiveRecord的验证错误消息显示属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文