Member-only story
Custom slugs for Rails URLs done right
I’ve seen a lot of examples of this online, and it took a while for me to get it right, so I decided to document it.
The two cases I’ve used this for:
- Vanity URLs, e.g. trying to open a user’s profile at
/u/amingilani
- Obfuscated URLs, e.g. trying to make the URL difficult to guess such as
/transactions/601585f7–0f4a-41e8-bd04-b2eb24262fb4
Both cases differ only by the fact that the slug is randomly generated in the latter.
Quick definitions:
Slug
: part of the URL to identify the recordPrimary key
: a unique identifier for database recordsUUID
: Universal unique identifier, a 128 bit generated identifier that depending on the implementation is either guaranteed or is very likely to be unique.
Overview:
- We’ll add a unique
slug
column to our database table - We’ll generate a unique slug on creation (only for the 2nd use-case)
- We’ll use the slugs in URLs
Adding a slug
column to our database
We’ll need to ensure that our slug is unique, and always present. You can name it “username” or anything more semantic if it’s meant to be part of the model.
class AddSlugToRecommendations < ActiveRecord::Migration[5.1]
def change
add_column :transactions, :slug, :string, null…