Make ids in URL Search engine friendly

July 26, 2006 at 10:32 am 1 comment

Generally in rails url are in form of :controller/:action:/:id for example post/view/9 .

URLs are considered extremely valuable. Not only because users have to see them all the time, but also because search engines give them a lot of weight: since it’s a “limited resource” where you can only include a few keywords, you better use the keywords that matter most.

We can use both post id and post title in the url to make them more search engine friendly as post/view/9-this-is-the-post-title.

This is simple, as rails treats :id as a special parameter in routes. It’s specialness comes from the fact that it would try to call the to_param method on any object passed when creating URLs. That’s why url_for :id => @post is equivalent to url_for :id => because ActiveRecord model’s have a default to_param that returns the id of the object.

All you need to do is define your own to_param for your models, and make sure you don’t explicitly include the .id in your url_for and link_to, because then you would be skipping your own to_param call.

  class Post < ActiveRecord::Base
    def to_param
      "#{id}-#{full_name.gsub(/[^a-z1-9]+/i, '-')}"

You can change -(hyphen) in gsub in to_param method by _, + or anything you wish.

Entry filed under: rails, RubyonRails. Tags: .

Plugin: validate_request converting all newline characters to br tag

1 Comment Add your own

  • 1. Ywqom  |  May 20, 2007 at 7:23 pm



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed

Important Notice…

I have moved this blog to . I will continue posting at, not on

Kindly update your book marks to

and .

I am really very sorry for inconvenience.

Comming Soon….

Domain for Sale

(Contact me)

Recent Posts


July 2006
« Jun   Aug »


  • Add to Google
  • Subscribe in NewsGator Online
  • Subscribe with Bloglines
  • WebOnRails on feedburner
  • technorati


Flickr Photos

A bellezza di a natura (C☺rsica)

JWL5932 Mountain Hare..

Black and Gold

More Photos

Visitor’s Location

Blog Stats

  • 17,978 hits

%d bloggers like this: