Question

I'm trying to generate some url 'slugs' for my website. It's based upon a single piece of user generated text.

Now, i have made my own slug method, so i'm not after some code for that.

What i'm wondering is where is the best place to determine if this slug is unique and then insert it because the slug field is a Unique Key Index.

Originally, i had a trigger on any insert (against the table) so when the data is entered, the slug is then determined. I had a function that checked for the number of records that contained the user's text (not the slug) and then generated the slug and added the record count + 1 to the end of the new slug.

eg.

5 records are found in the table with the same User generated content. the slug for this now the slug-text with a 6 added to the end.

Flaws: if the user changes their text, the slug doesn't change.

Anyways, i'm wondering if other people have delt with this issue before and found any ways to fix it?

Was it helpful?

Solution

I kinda like the way stackoverflow does it. Which is to put both the ID and the slug into the url. Now the slug no longer has to be unique. I believe hulu.com does it this way as well. I think it's a practical solution to the problem.

OTHER TIPS

Most sites don't change the slug for the reason that if a user edits her title it shouldn't break any links to the post that have already been made.

For the database solution you already have, if it works well you can have an update trigger as well to update the slug if the content changes, but you should look for the performance hit.

For an alternate solution, you can use a map [loaded at start up containing existing slugs] that contains the key as the slug and existing count as value. Each time you generate a slug , determine the existing value and append the value higher than it in the table and thereafter update the map.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top