如何自定义 rails activerecord 验证错误消息以显示属性值 [英] how to customize rails activerecord validation error message to show attribute value

查看:16
本文介绍了如何自定义 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 件事:

  1. 验证消息使用 Rails I18n 样式插值,即 %{value}
  2. 关键是 value 而不是 name,因为在国际化的上下文中,您并不真正关心模型的其余部分.
  1. The validation messages use the Rails I18n style interpolation, which is %{value}
  2. The key is value rather than name, 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆