如何验证唯一性,然后在失败时提出独特的替代方案
我想根据标题字段创建 slugs,因此这些 slugs 必须是唯一的。
当 validates_uniqueness_of 失败时是否有回调方法,以便我可以将一个字符附加到 slug 的末尾以使其唯一?
I want to create slugs based on a title field, so those slugs will have to be unique.
Is there a callback method for when validates_uniqueness_of fails so that i can append a character to the end of the slug to make it unique?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
听起来这作为 before_create 回调比验证更好。如果名字是假的,那么它实际上并不是无效的;你只需要唯一化它。
Sounds like this would be better as a before_create callback than a validation. It's not actually invalid if the name's a dupe; you just need to uniquify it.
您不必使用
validates_uniqueness_of
,您始终可以自己执行此操作,然后自定义消息。例如:如果用户名已被使用,则建议用户名末尾附加“1”。
You don't have to use
validates_uniqueness_of
, you can always do it yourself and then customize the message. For example:If username is already taken, suggest the username with "1" appended to the end of it.