Nithin Bekal Posts About

Friendly URLs in Rails using to_param

01 Mar 2010

I’ve wondered about how rails websites like Railscasts created SEO friendly URLs. I read this post by Obie Fernandez which explains how to do this.

I’ve never had to use SEO friendly URLs in my projects so far and I assumed that generating these URLs is very complicated and some plugin might be at work. And like always, Rails proved me wrong and I’m amazed at how simple this is.

Suppose you had a RESTful resource called posts that had title and content fields. If you wanted the post page URLs to contain text from the title, you just have to add this to_param method to the Post model:

class Post
  # other stuff here

  def to_param
    "#{id}-#{title.gsub(/[^a-z0-9]+/i, '-')}"

Now if you had a post whose title was “SEO friendly URLs”, and in your view you had <%= link_to @post.title, @post %> where @post is an instance of the Post model representing the “SEO friendly URLs” post. This will generate the following path: /posts/1-SEO-friendly-URLs.

As explained in Obie’s post, this will only work if you pass an instance of Post as the id parameter and the actual id itself. You don’t have to change anything in the controller to make this work.

This is just another one of those little tricks I discovered in rails that originally looked difficult but is actually incredibly easy to accomplish.

Nithin Bekal
Hi, I’m Nithin! This is my blog about programming. Ruby is my programming language of choice and the topic of most of my articles here, but I occasionally also write about Elixir, and sometimes about the books I read. I'm @nithinbekal on Twitter.