website logo

← All articles

Add a multi-tenant URLs on a Rails app

How to improve a Rails platform user experience with a simple multi-tenancy URL scheme.

With a real world application, you inevitably hit the point where Invoice#30420 in a URL feels wrong. It exposes your primary keys, it leaks volume, and in a multi-tenant context, it’s completely ambiguous.

The sequenced gem offers a surgical solution to this problem. It doesn’t try to replace your primary keys or force you into UUIDs. Instead, it adds a scoped sequential identifier ie. a “human-readable” number that resets for each tenancy scope. For our platform, that scope is Organization.

Here is how we typically implemented clean, per-tenant URLs without sacrificing database integrity.

The Setup: Adding the Sequential Column

The gem is deliberately unopinionated about your schema, but it requires an integer column to store the sequence. By default, it looks for sequential_id, but I prefer explicitness in multi-tenant schemas.

For this example, let’s say we have Project and Invoice models that belong to an Organization. We want each organization to have its own Project#1, Project#2, and independently, its own Invoice#1, Invoice#2.

Migration:

class AddSequentialIds < ActiveRecord::Migration[7.1]
  def change
    add_column :projects, :sequential_id, :bigint
    add_column :invoices, :sequential_id, :bigint

    # Critical for data integrity: unique within the tenant scope
    add_index :projects, [:organization_id, :sequential_id], unique: true
    add_index :invoices, [:organization_id, :sequential_id], unique: true
  end
end

A note on concurrency: The sequenced gem uses table-level locking to calculate the next number (SELECT MAX(...) FOR UPDATE). It is only safe for concurrent writes on PostgreSQL. If you are on MySQL, you need to be aware of potential race conditions. For a high-volume SaaS, the locking overhead is a trade-off you accept for readable numbers; if you outgrow it, you may need to move to a counter-cache or a dedicated sequence table.

The Model: Scoping to the Organization

The magic happens in the model. We tell sequenced to scope the counter to the organization_id. This ensures that when Organization A creates its 5th project, it gets 5, even if Organization B has already created 100 projects.

class Project < ApplicationRecord
  belongs_to :organization

  acts_as_sequenced scope: :organization_id, column: :sequential_id
end

Because both Project and Invoice are scoped to the same Organization, they will maintain independent sequences. Organization A’s first project is 1, and its first invoice is also 1.

The Critical Change: models to_param

This is where the URL hygiene happens. By default, Rails calls to_param on a model, which returns the id (the primary key). We need to override this in every model that participates in the tenant-scoped URL scheme.

class Project < ApplicationRecord
  belongs_to :organization
  acts_as_sequenced scope: :organization_id, column: :sequential_id

  def to_param
    sequential_id.to_s
  end
end
class Invoice < ApplicationRecord
  belongs_to :organization
  acts_as_sequenced scope: :organization_id, column: :sequential_id

  def to_param
    sequential_id.to_s
  end
end

The final model code is just a few lines, and since we always look to DRY things, so we can even put all these in a shared concern (I used WithinPlatformOrganizationTenancy in my app code).

require "active_support/concern"

module WithinPlatformOrganizationTenancy
  extend ActiveSupport::Concern

  included do
    acts_as_sequenced scope: :organization_id
  end

  def to_param
    sequential_id.to_s
  end
end
class Project < ApplicationRecord
  include WithinPlatformOrganizationTenancy

  belongs_to :organization # I prefer keeping associations declarations within the model
end
class Invoice < ApplicationRecord
  include WithinPlatformOrganizationTenancy
  
  belongs_to :organization # idem here
end

Why to_s?

Rails expects to_param to return a string. While sequential_id is an integer, returning it directly usually works due to implicit coercion in URL helpers, but returning .to_s is the correct contract. More importantly, it prevents subtle issues if the value is ever nil (though sequenced ensures it is set via a before_validation callback in modern versions).

The Controller: Fetching by sequence, not ID

Your to_param change breaks your default controller lookups. organization.projects.find(params[:id]) will now try to find a Project where id = 1, but params[:id] is now 1 (the sequence). This will work only for the very first project of the organization. For everyone else, it will either 404 or, worse, show the wrong record.

From now on, you must query every lookup by sequential_id.

class ProjectsController < ApplicationController
  before_action :set_organization

  def show
    # DO NOT use Project.find(params[:id])
    @project = @organization.projects.find_by!(sequential_id: params[:id])
  end

  private

  def set_organization
    # Assuming you have a current_organization helper from your tenancy setup
    @organization = current_organization
  end
end

Routing Considerations

If your URLs are nested under the organization slug (e.g., /:org_slug/projects/:id), the routing layer remains blissfully unaware of the sequenced gem. It just passes the sequence string "5" into the URL helpers transparently because we told the model to behave so with the to_param definition. The controller does the heavy lifting of interpreting that "5" as a sequential_id scoped to the tenant.

The Trade-off

By adopting sequenced, you trade a tiny bit of write throughput (due to the locking) for a massive gain in URL clarity and perceived tenancy isolation. When a user of Organization C sees https://app.example.com/projects/12, they know they are looking at the 12th project of their organization. They aren’t looking at a global counter that tells the world how many projects your platform has processed.

The to_param override is the linchpin. Without it, the sequence exists but never reaches the browser. With it, your URLs become a natural extension of your tenancy model.