Question
How do I generate pretty URLs in Ruby on Rails?
For example, I have a URL like this for a post:
https://example.com/posts/123
How can I get pretty URLs (SEO URLs) for all posts?
https://example.com/posts/123-the-title-of-my-post
Answer
In a Ruby on Rails application is extremely simple to generate pretty URLs (search engine friendly URLs).
In order to move from these URLs:
https://example.com/posts/123
To these URLs:
https://example.com/posts/123-the-title-of-my-post
You just need to add this to your model (e.g. Post
):
def to_param
"#{id}-#{title.parameterize}"
end
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
end
end