如何自定义rails activerecord验证错误消息以显示属性值
当用户尝试使用已存在的名称创建记录时,我想显示一条错误消息,例如:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有两件事:
% {value}
value
而不是name
,因为在国际化的背景下,您并不真正关心模型的其余部分。所以你的代码应该是:
2 things:
%{value}
value
rather thanname
, because in the context of internationalization, you don't really care about the rest of the model.So your code should be:
看起来您可以将
Proc
传递给消息。执行此操作时,您将获得两个参数::activerecord.errors.models.user.attributes.name.taken
的符号因此,如果您允许进程上有两个参数,则可以使用
attributes[:value]
获取所使用的名称的项目:It looks like you can pass a
Proc
to the message. When you do this, you get two parameters::activerecord.errors.models.user.attributes.name.taken
So if you allow for two parameters on a proc, you can use the
attributes[:value]
item to get the name that was used:您使用什么版本的 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.