Custom slugs for Rails URLs done right

Amin Shah Gilani
2 min readJul 14, 2017


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:

  1. Vanity URLs, e.g. trying to open a user’s profile at /u/amingilani
  2. 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 record
  • Primary key: a unique identifier for database records
  • UUID: Universal unique identifier, a 128 bit generated identifier that depending on the implementation is either guaranteed or is very likely to be unique.


  1. We’ll add a unique slug column to our database table
  2. We’ll generate a unique slug on creation (only for the 2nd use-case)
  3. 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…



Amin Shah Gilani

Founder. Developer. Spaces over tabs. Atom over your favorite X.