When you are creating something for the web, you have to keep in mind that your website must be as easy to find as possible.
SEO, or Search Engine Optimization (http://en.wikipedia.org/wiki/Search_engine_optimization) should always be in your mind when designing and creating your website.
Lets imagine a blog. By default the route to each post would be something like:
which works just fine.
But this is not SEO friendly, as the search engine crawlers won’t link the URL to the content.
A more friendly URL would include the post title, so the crawler links it directly to the content. Although this raises a problem: what about special chars?
Well, this little workaround does the trick. The idea is for a post with a title like “This is the post title :)” to create a url like this “this-is-the-post-title”.
Downcasing and replacing all the non letters and non numeric characters.
Let’s see how:
1 – Create a field called url on your class/table
2 – Create a helper class called SeoHelper in a file called seo_helper.rb, with the following content
class SeoHelper def self.to_url (sentence) sentence.downcase.gsub(/[^a-z0-9]+/i, '-') end end
3 – Before saving your object, populate the url with method provided by the helper class
def Save post = Post.new(params[:post]) post.url = SeoHelper.to_url(post.title) post.save ... end
4 – On the blog page, look for the url field instead of the post id.