Pretty URLs in Ruby on Rails


How do I generate pretty URLs in Ruby on Rails?

For example, I have a URL like this for a post:

How can I get pretty URLs (SEO URLs) for all posts?


In a Ruby on Rails application is extremely simple to generate pretty URLs (search engine friendly URLs).

In order to move from these URLs:

To these URLs:

You just need to add this to your model (e.g. Post):

def to_param

Everything else (including routes, controllers, views, helpers, etc.) work as expected and you don’t need to change them.

Optionally, if you want to avoid duplicated URLs when the title changes, you can use a 301 redirect in your controller:

  def show
    @post = Post.find(params[:id])
    if params[:id] != @post.to_param
      redirect_to post_path(@post), status: :moved_permanently