如何自定义rails activerecord验证错误消息以显示属性值

发布于 2024-11-08 12:39:05 字数 234 浏览 0 评论 0原文

当用户尝试使用已存在的名称创建记录时,我想显示一条错误消息,例如:

name“some name”已被占用

我一直在尝试这样做:

validates_uniqueness_of :name, :message => "#{name} has already been taken"

但这输出表名而不是 name 属性的值

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" has already been taken

I have been trying to do:

validates_uniqueness_of :name, :message => "#{name} has already been taken"

but this outputs the table name instead of the value of the name attribute

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

找个人就嫁了吧 2024-11-15 12:39:05

有两件事:

  1. 验证消息使用 Rails I18n 样式插值,即 % {value}
  2. 关键是 value 而不是 name,因为在国际化的背景下,您并不真正关心模型的其余部分。

所以你的代码应该是:

validates_uniqueness_of :name, :message => '%{value} has already been taken'

2 things:

  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.

So your code should be:

validates_uniqueness_of :name, :message => '%{value} has already been taken'
-黛色若梦 2024-11-15 12:39:05

看起来您可以将 Proc 传递给消息。执行此操作时,您将获得两个参数:

  1. 类似于 :activerecord.errors.models.user.attributes.name.taken 的符号
  2. 类似于“{:model=>”的哈希值"User", :attribute=>"Name", :value=>"My Name"}

因此,如果您允许进程上有两个参数,则可以使用 attributes[:value]获取所使用的名称的项目:

validates_uniqueness_of :name, 
                        :message => Proc.new { |error, attributes| 
                          "#{attributes[:value]} has already been taken." 
                        }

It looks like you can pass a Proc to the message. When you do this, you get two parameters:

  1. A symbol along the lines of :activerecord.errors.models.user.attributes.name.taken
  2. A hash that looks something like `{:model=>"User", :attribute=>"Name", :value=>"My Name"}

So if you allow for two parameters on a proc, you can use the attributes[:value] item to get the name that was used:

validates_uniqueness_of :name, 
                        :message => Proc.new { |error, attributes| 
                          "#{attributes[:value]} has already been taken." 
                        }
旧时光的容颜 2024-11-15 12:39:05

您使用什么版本的 Rails?

如果 Rails 3. 那么据我了解你应该使用 :message => '%{value} 已被占用'。我不确定 Rails 2.3. - 但无论如何,您都可以创建自己的自定义验证来执行您需要的操作。

What version of Rails do you use?

If Rails 3. then as i understand you should use :message => '%{value} has already been taken'. I am not sure about Rails 2.3. - but in any case you can create your own custom validation that performs what you need.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文