Building BandTools: Sluggable Concern
4 December 2026
In the previous BandTools post I wrote about merge tags, which fill in placeholders when a newsletter is rendered. This time the subject is something every newsletter gets before it is ever sent: a readable URL.
When a musician writes a newsletter called “Tour Diary” in BandTools, its archive page lives at /u/username/newsletters/tour-diary rather than at a numeric ID. That last path segment is the slug. Automatic newsletters, which are created from an RSS or Atom feed, and the service updates I can send to every account need slugs too. Rather than repeat the same callbacks and validations in three models, they share a Rails concern called Sluggable.
Including the concern is not enough on its own. Each model opts in with a class macro that says which attribute the slug comes from:
class Newsletter < ApplicationRecord
include Sluggable
slug_from :subject, scope: :user,
resource_name: "newsletter",
reserved: RESERVED_SLUGS
end
class FeedSource < ApplicationRecord
include Sluggable
slug_from :name, scope: :user,
resource_name: "automatic newsletter"
end
class ServiceUpdate < ApplicationRecord
include Sluggable
slug_from :subject, resource_name: "service update"
end
If you read the sudo mode post, this will look familiar. There, the require_sudo_for macro stored a list of protected actions on the controller class. slug_from works the same way, but it has more to remember, so it uses class_attribute to keep each option on the model class:
module Sluggable
extend ActiveSupport::Concern
class_methods do
def slug_from(attribute, scope: nil,
resource_name: nil, reserved: [])
class_attribute :slug_source_attribute,
instance_writer: false, default: attribute
class_attribute :slug_scope_attribute,
instance_writer: false, default: scope
class_attribute :slug_resource_label,
instance_writer: false,
default: resource_name || model_name.human.downcase
class_attribute :slug_reserved_words,
instance_writer: false,
default: reserved.map(&:to_s).freeze
before_save :set_slug
validate :slug_source_must_not_collide_with_existing_slug
end
def find_by_param!(param)
find_by!(slug: param)
end
end
def to_param
slug
end
end
Calling slug_from does three things. It records the options, registers a before_save callback that writes the slug, and adds a validation that catches collisions. Passing instance_writer: false means a record cannot quietly change its own configuration; the options belong to the class.
The other two methods connect the slug to routing. Rails calls to_param whenever it builds a URL from a record, so overriding it means every path helper produces tour-diary rather than 42 without any changes to views. find_by_param! is the other direction, and controllers use it to load the record from params[:id]:
@newsletter = Current.user.newsletters
.find_by_param!(params[:id])
Because the lookup goes through Current.user.newsletters, a slug only has to be unique for one musician. Two artists can both write “Tour Diary” without either of them noticing.
Generating the slug is a single call to parameterize, plus one special case that I will come back to:
def set_slug
candidate = public_send(self.class.slug_source_attribute)
.to_s.parameterize
if self.class.slug_reserved_words.include?(candidate)
label = self.class.slug_resource_label.parameterize
candidate = "#{candidate}-#{label}"
end
self.slug = candidate
end
parameterize lowercases the text, transliterates accented characters, and collapses everything else into hyphens, so “Mixing the Bridge” becomes mixing-the-bridge. Because the callback runs on every save, renaming a draft renames its URL as well.
That conversion is lossy, which is where the validation comes in. “Mixing the Bridge” and “mixing-the-bridge” are different subjects, but they produce the same slug. Many slug libraries resolve this by quietly appending a suffix, so the second one becomes something like mixing-the-bridge-2. I would rather the musician chose a subject they are happy with, so BandTools tells them instead:
def slug_source_must_not_collide_with_existing_slug
source = public_send(self.class.slug_source_attribute)
return if source.blank?
candidate_slug = source.to_s.parameterize
return if candidate_slug.blank?
relation = slug_collision_scope(candidate_slug)
return if relation.nil?
relation = relation.where.not(id: id) if persisted?
relation = relation.where.not(
self.class.slug_source_attribute => source
)
return unless relation.exists?
errors.add(self.class.slug_source_attribute,
"is too similar to an existing " \
"#{self.class.slug_resource_label}")
end
Two exclusions keep the message accurate. The record is never compared with itself, and records whose subject is exactly the same are skipped. Newsletter already has a uniqueness validation on subject with its own message, “has been used for a previous newsletter”, so this check only covers the case that one misses: different text, same slug. One mistake produces one error.
The resource label is what makes the message read naturally. A newsletter is “too similar to an existing newsletter”, and a feed is “too similar to an existing automatic newsletter”. When no label is given, the concern falls back to the model’s human name.
The scope option decides where to look for collisions:
def slug_collision_scope(candidate_slug)
if self.class.slug_scope_attribute
owner = public_send(self.class.slug_scope_attribute)
return nil if owner.nil?
owner.public_send(self.class.model_name.collection)
.where(slug: candidate_slug)
else
self.class.where(slug: candidate_slug)
end
end
With scope: :user, the concern asks the owner for its own collection. model_name.collection returns "newsletters" for Newsletter and "feed_sources" for FeedSource, so the same line works for both models without either one naming its association. Service updates are written by administrators and do not belong to any one account, so they have no scope and their slugs are unique across the whole site.
The reserved option came from a bug. Musicians on the Headliner plan can publish their newsletter archive on their own domain, where each newsletter lives at the root: example.com/tour-diary. That domain also has a few fixed routes, such as the error pages and the subscription confirmation page, and they are matched before the newsletter route. A newsletter called “404!!” would get the slug 404 and become unreachable, because the error page would always answer first. The same problem applied to the owner’s own newsletter list pages, such as drafts and sent.
Newsletter passes those words in as RESERVED_SLUGS. When a slug would clash with one, set_slug adds the resource label, so “Drafts” becomes drafts-newsletter. The newsletter stays reachable, and the fixed route keeps working.
The concern has its own tests, which use Newsletter and ServiceUpdate as the host models. The first checks the scoped collision rule; the second, from the Newsletter tests, checks the reserved words:
test "scoped slug-collision validator rejects parameterise-equivalent siblings" do
Newsletter.create!(subject: "Mixing the Bridge",
message: "Hello", user: @user, draft: true)
duplicate = Newsletter.new(subject: "mixing-the-bridge",
message: "Hello", user: @user,
draft: true)
assert_not duplicate.valid?
assert duplicate.errors[:subject].any? { |msg|
msg.include?("is too similar to an existing newsletter")
}
end
test "newsletters do not take the slugs of the owner's newsletter list pages" do
{ "Drafts" => "drafts-newsletter", "Held!" => "held-newsletter",
"New!!" => "new-newsletter", "Sent!" => "sent-newsletter" }
.each do |subject, slug|
newsletter = Newsletter.create!(subject:, message: "test",
user: @user, draft: true)
assert_equal slug, newsletter.slug
end
end
Sluggable started life as three copies of the same few methods in three models, before I pulled them together. Now a new model that needs a readable URL gets one with a single line, and the subtle parts, such as near-duplicate subjects and routes that would shadow a slug, are solved once. That is the kind of concern I like best: small enough to read in one sitting, and specific enough that the models using it stay short.