Suppose I access article at
/article/23/the-46-year-old-virgin
in /article/id/slug
form.
I can obviously use id to fetch the data in the view.
Then I don't see a reason I would store the slug in a database.
besides, /article/id/slug
isn't better than /article/slug
?
The problem with only using the id
is that it will hurt both URL readability and search engine optimization. (See here for the latter.)
One problem with only using the slug
is that they are long and URLs sometimes get truncated in the real world. If you have the id
at the beginning then you just use that for lookups and redirect if something went wrong with the slug
part. The other problem is that you have to guarantee that your slugs
will always be unique. Are you sure you'll never want to have two articles with the same title?
So doing one or the other is certainly possible, but there are benefits to doing both.
As to whether or not you should store the slug in the database, first decide if you want the URL to change when the title changes. One advantage to keeping it the same is that you will then have a single, permanent, canonical URL for your resource, one that won't change if you need to edit the title. The obvious downside is that your URL will no longer reflect the exact title of the article.
If you always want the slug to match the title, then this becomes a standard database denormalization question - the slug will represent redundant (derived) information that you're precomputing for performance reasons. I probably wouldn't bother, myself.
If you want the URL to stay the same even if the title is edited, you will of course have to store the slug separately.