Rails:如果永久链接已被占用,则将编号附加到永久链接

发布于 2024-11-19 17:02:41 字数 433 浏览 10 评论 0原文

如果已经有 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 技术交流群。

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

发布评论

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

评论(1

╭ゆ眷念 2024-11-26 17:02:41

首先,问问自己:有没有更简单的方法来做到这一点?我相信有。如果您已经愿意向您的 slug 添加数字,那么总是添加一个数字(例如 ID)怎么样?

before_validation :generate_slug

private
def generate_slug
  self.permalink = "#{self.id}-#{self.name.parameterize}"
end

这是一种非常可靠的方法,您甚至可以将 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?

before_validation :generate_slug

private
def generate_slug
  self.permalink = "#{self.id}-#{self.name.parameterize}"
end

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.

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