Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a sequential unique id for a db field

I have the table Slug with the field url which is unique.

If I create @slug = Slug.url = "foo"

When I go to save, if Slug.url of "foo" already exists, I would like to then try for a Slug.url of "foo-1" if that also exists, try "foo-2" foo-3, foo-4, etc. until a value is found that doesn't exist and can be created in the database. What would be the right way to go about this in my Rails model?

Update

My latest code looks like this:

  def set_url
    self.url = self.title.parameterize
    # Ensure the url is available
    qUrl = self.url.split('-').shift
    slugs = Slug.where("url like '#{qUrl}%'")
    if slugs.exists?
      c = slugs.count + 1
      self.url = self.url + "-" + c.to_s
    end
  end

The problem with this code is the qUrl is picking up false positives, any time a title starts with the word "why" slugs are being found. Is there an approach that is more reliable and elegant?

like image 314
AnApprentice Avatar asked Jan 04 '23 19:01

AnApprentice


1 Answers

I'd suggest using the friendly_id gem for this. If you look at the documentation in the slugged object, you'll see that it has a mechanism to handle uniqueness by appending a uuid to the slug name.

Alternatively, there are a number of other slug generating gems that might work better for your environment.

like image 174
11 revs, 10 users 40% Avatar answered Jan 13 '23 10:01

11 revs, 10 users 40%