tags:

views:

1258

answers:

3

Hi folks,

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?

+2  A: 

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.

alxp
A: 

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.

Nrj
+6  A: 

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.

toby
@toby Stackoverflow actually appears to use the slug portion of the URL for seo purposes only (maybe there are other reasons I'm not aware of). I say this because for any given question, the URL http://stackoverflow.com/questions/434376/title-of-post and http://stackoverflow.com/questions/434376 and http://stackoverflow.com/questions/434376/total-random-gobblygoo all resolve to the particular question ID referenced in the URL.
Howiecamp