Simply put, permalinks are great for SEO, but not only that, they make our URLs human readable for easier identification.
For blogs, just like tags and comment systems, they’re a must (or a standard I should say.)
Permalink generation
Case: Say your Post model has a ‘permalink’ field that will contain a string value of your automatically generated permalink.
When you submit a new post, simply do the usual new and save commands in your Controller. For example:
@post = Post.new(params[:post])
if @post.save
flash[:notice] = "Post '#{@post.title}' saved successfully"
# and so on...
end
Now open up your Post model and add the following filter:
before_create :generate_slug
This will make sure that before a new post is saved, generate_slug function will execute automatically.
Below in your Post model, add the actual meat of this action:
protected
def generate_slug
self.permalink = title.gsub(/\W+/, ' ').strip.downcase.gsub(/\ +/, '-')
end
This simply takes the title attribute and passes it through a few RegEx replacements leaving you with a nice permalink.
For some reason, it took me a while to find this snipped online, so I wanted to make it available for other beginners. (Probably because everyone else just writes their own RegEx!)
Things to improve
» Make sure permalink isn’t already in use (thanks Joel)
» Make sure permalink isn’t too long (thanks Jason)
Other options
This could simply be done with JavaScript as another alternative.
Joel
over 2 years ago
Still need to fix the overflow situation there dimitry ;)
Something to consider should be the existence of a duplicate post. Perhaps add something to your protected method ;)