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 => @post.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, '-')}"
    end
  end

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

Share this: