Rails:如果永久链接已被占用,则将编号附加到永久链接
如果已经有 john-doe,我想给 John Doe 永久链接 john-doe-2 -1。 该编号应该是要附加的下一个免费编号(“john-doe-n”)
目前我的永久链接是按通常的方式生成的:
before_validation :generate_slug
private
def generate_slug
self.permalink = self.name.parameterize
end
如何实现 validates_uniqueness_of 之类的方法,将这种数字添加到 self.permalink 中,然后正常保存用户?
I would like to give John Doe the permalink john-doe-2, if there already is a john-doe-1.
The number should be the next free one to be appended ("john-doe-n")
Currently my permalinks are generated the usual way:
before_validation :generate_slug
private
def generate_slug
self.permalink = self.name.parameterize
end
How to implement a validates_uniqueness_of-like method, that adds this kind of number to self.permalink and then saves the user normally?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,问问自己:有没有更简单的方法来做到这一点?我相信有。如果您已经愿意向您的 slug 添加数字,那么总是添加一个数字(例如 ID)怎么样?
这是一种非常可靠的方法,您甚至可以将 slug 直接传递给 find 方法,这意味着您根本不需要保存 slug。
否则,您可以只检查姓名+号码是否已存在,并将n加1,然后重新检查,直到找到空闲号码。请注意,如果有大量同名记录,这可能需要一段时间。如果同时生成两个段,这种方式也会受到竞争条件的影响。
First of all, ask yourself: Is there a simpler way to do this? I believe there is. If you're already willing to add numbers to your slug, how about always adding a number, like the ID?
This is a very robust way of doing it, and you can even pass the slug directly to the
find
method, which means that you don't really need to save the slug at all.Otherwise, you can just check if the name + number already exists, and increment n by 1, then recheck, until you find a free number. Please note that this can take a while if there are a lot of records with the same name. This way is also subject to race conditions, if two slugs are being generated at the same time.