HackerNoon.com

Elijah McClain, George Floyd, Eric Garner, Breonna Taylor, Ahmaud Arbery, Michael Brown, Oscar…

Follow publication

Member-only story

Custom slugs for Rails URLs done right

Amin Shah Gilani
HackerNoon.com
Published in
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.

Overview:

  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…

--

--

HackerNoon.com
HackerNoon.com

Published in HackerNoon.com

Elijah McClain, George Floyd, Eric Garner, Breonna Taylor, Ahmaud Arbery, Michael Brown, Oscar Grant, Atatiana Jefferson, Tamir Rice, Bettie Jones, Botham Jean

Amin Shah Gilani
Amin Shah Gilani

Written by Amin Shah Gilani

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

Responses (4)

Write a response