ruby
27 lines · 7 steps
How URL slugs work in Rails
An Article generates a unique, URL-safe slug before validation and uses it in route helpers.
Explained by
highlit
1class Article < ApplicationRecord
2 before_validation :generate_slug, on: :create
3
4 validates :slug, presence: true, uniqueness: true,
5 format: { with: /\A[a-z0-9]+(?:-[a-z0-9]+)*\z/ }
6
7 def to_param
8 slug
9 end
10
11 private
12
13 def generate_slug
14 return if slug.present? || title.blank?
15
16 base = title.parameterize
17 candidate = base
18 suffix = 2
19
20 while self.class.where(slug: candidate).exists?
21 candidate = "#{base}-#{suffix}"
22 suffix += 1
23 end
24
25 self.slug = candidate
26 end
27end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A before_validation callback lets you derive a field before the same field's validations run.
- 2Looping while a uniqueness query matches guarantees a collision-free slug at generation time.
- 3Overriding to_param makes Rails route helpers use a readable identifier instead of the numeric id.
Related explainers
ruby
class ToastBroadcaster include ActionView::RecordIdentifier def self.broadcast_to(user, message:, type: :notice)
How Turbo Stream toasts broadcast in Rails
turbo-streams
service-object
real-time
Intermediate
6 steps
ruby
class TemplateInterpolator PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/ def initialize(strict: false)
Interpolating templates with dotted keys in Ruby
regex
string-interpolation
hash-traversal
Intermediate
6 steps
go
package handlers import ( "net/http"
Serving embedded static meta files in Gin
embedding
static assets
http caching
Intermediate
6 steps
ruby
class KeyTransformer def self.camelize(data) new.camelize(data) end
Recursively camelizing nested Ruby data
recursion
data-transformation
pattern-matching
Intermediate
7 steps
ruby
module Paginatable extend ActiveSupport::Concern private
A reusable pagination concern in Rails
pagination
concerns
http-headers
Intermediate
8 steps
ruby
class Api::MessagesController < ApiController before_action :authenticate_api_key! rate_limit to: 100,
Layered API rate limiting in Rails
rate-limiting
api-authentication
throttling
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/how-url-slugs-work-in-rails-explained-ruby-9e0f/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.