This course came at the perfect time. I’ve recently gotten back into Rails after an 18-year hiatus, and this was a perfect refresher and shows just how much you can accomplish with Rails right out of the box.Garrett Winder
The next feature I want to add to our application is SEO-friendly and self-healing URLs for the post show view.
Right now, our application uses auto-incrementing integer IDs as the identifier in our post URLs. This is problematic for two main reasons:
To improve search engine rankings and user experience, we want to embed the post title into the URL. However, post titles can change over time, so we need a way to maintain a canonical URL that always brings users back to the correct post.
To support SEO-friendly URLs, we’ll use virtual columns, a feature we previously discussed.
We define a public ID column, which consists of a hex-encoded combination of:
To make this work, we need to override the find method in our Post model:
This ensures that even if the title changes, the post remains accessible via its public ID.
Rails makes it easy to define how models are parameterized into URLs using the to_param method.
Here’s how we construct the SEO-friendly URL:
This results in readable and search-engine-friendly URLs like:
/posts/my-awesome-blog-post-3af2b8
A self-healing URL means:
Since our find method only looks at the last segment (the public ID), the URL remains resilient to minor changes.
To ensure that every post resolves to its correct canonical URL, we update our PostsController:
before_action :ensure_canonical_url, only: %i[ show edit update destroy ]
def ensure_canonical_url
redirect_to @post if @post.to_param != params[:id]
end
Now, no matter how much users alter the URL, they always land on the right page with the correct format.
To confirm our index is working, we:
This ensures fast lookups, even in a large database.
Up next, we’ll dive into full-text search, using SQLite’s built-in search engine to enable powerful search functionality in our application.