如何自定义 rails activerecord 验证错误消息以显示属性值 [英] how to customize rails activerecord validation error message to show attribute value
本文介绍了如何自定义 rails activerecord 验证错误消息以显示属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当用户尝试使用已存在的名称创建记录时,我想显示如下错误消息:
When a user tries to create a record with a name that already exists, I want to show an error message like:
name "some name" 已经被占用
我一直在努力:
validates_uniqueness_of :name, :message => "#{name} has already been taken"
但这会输出表名而不是 name 属性的值
but this outputs the table name instead of the value of the name attribute
推荐答案
2 件事:
- 验证消息使用 Rails I18n 样式插值,即
%{value}
- 关键是
value
而不是name
,因为在国际化的上下文中,您并不真正关心模型的其余部分.
- 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.
所以你的代码应该是:
validates_uniqueness_of :name, :message => '%{value} has already been taken'
这篇关于如何自定义 rails activerecord 验证错误消息以显示属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文