Multi-tenancy in Rails: acts_as_tenant, Apartment and database-per-tenant compared

A Rails app sold to companies rather than individuals sooner or later needs the same guarantee: the users of one customer account never see another account's records. That customer is the tenant, and there are three ways to keep tenants apart: a tenant column on every table, a database schema per tenant, or a whole database per tenant. Each has a gem, and since Rails 6.1 the framework itself covers part of the third. The choice is hard to reverse later, so it is worth making with the trade-offs in view.
Release figures are from RubyGems.org, November 2026. The current Rails line is 8.1.
Three ways to separate tenants
- Row level. All tenants share the same tables, and every tenant-owned row carries an
account_id. Isolation depends on every query including that condition. Cheap to run, simple to migrate, and cross-tenant reporting is an ordinary query. - Schema level. On PostgreSQL, each tenant gets a schema containing a full copy of the tables, and the connection's
search_pathdecides which one a query reads. A forgottenWHEREcannot leak data, but every migration runs once per tenant. - Database level. Each tenant has its own database, or its own SQLite file. The strongest isolation, per-tenant backups and restores for free, and the most connections and moving parts to manage.
A useful rule of thumb from the maintainers themselves: row level suits many small tenants and greenfield apps; schemas or databases suit fewer, larger customers with contractual or regulatory isolation requirements, and retrofitting an app that was built single-tenant.
acts_as_tenant: the row-level default
acts_as_tenant (2.2.2, October 2026, MIT) has been the standard row-level gem for more than a decade, and went through a security-focused 2.0 release in September 2026 followed by three minor versions in October. You declare the tenant once per model and tell controllers how to find it:
class Project < ApplicationRecord acts_as_tenant :account validates_uniqueness_to_tenant :name end class ApplicationController < ActionController::Base set_current_tenant_by_subdomain(:account, :subdomain) end
The scoping is a default_scope: once a tenant is set, Project.all, find, update_all and destroy_all only see that account's rows, new records receive its id, and since 2.0 a record assigned to another tenant, or a belongs_to pointing at another tenant's record, fails validation. acts_as_tenant :account declares the belongs_to itself, so do not add your own. The current tenant lives in ActiveSupport::CurrentAttributes, so it is reset at the end of each request and job.
The weakness of row-level tenancy is everything that bypasses the default scope, and the README now lists it plainly: any query made when no tenant is set, unscoped, raw SQL through find_by_sql or connection.execute, counter-cache updates, and update_column. upsert_all matches rows by primary key across all tenants, so it must never receive ids from user input. Two settings close most of the gap. config.require_tenant = true raises ActsAsTenant::Errors::NoTenantSet for any query on a tenant model without a tenant, and accepts a lambda so that an admin area can opt out. config.tenant_change_hook runs whenever the tenant changes, which is the place to set a PostgreSQL session variable and let row-level security policies in the database refuse what the application forgets; the hook must also handle nil, or a pooled connection keeps the previous tenant's setting.
Apartment and ros-apartment: one schema per tenant
The original Apartment gem made schema-per-tenant popular, but its last release, 2.2.1, dates from June 2019. Development continues in a fork published as ros-apartment, maintained by CampusESP since 2024 and loaded with the same require "apartment". The stable line is 3.4.4 (May 2026, MIT), which requires Rails 7.0 or later:
# config/initializers/apartment.rb
Apartment.configure do |config|
config.excluded_models = %w[Account]
config.tenant_names = -> { Account.pluck(:subdomain) }
end
Rails.application.config.middleware.use Apartment::Elevators::Subdomain
Apartment::Tenant.switch("acme") { Project.count }
"Elevators" are Rack middleware that pick the tenant from the request; excluded_models stay in the shared public schema. Middleware order matters: an elevator placed after Devise's Warden middleware lets authentication run in the wrong schema, which the README addresses with insert_before Warden::Manager. The costs are operational. Every migration runs in every schema, so a deploy with a slow migration takes as many times longer as you have tenants, and the project's own documentation points teams with hundreds of tenants or more towards row-level tenancy instead.
A 4.0 rewrite has been in alpha since April 2026 (4.0.0.alpha15 in September). It replaces the switching of search_path on a shared connection with one connection pool per tenant, targets Rails 8.1 and Ruby 3.3, and changes the configuration. Stay on 3.4 for production for now, and read the upgrade guide before moving.
A database per tenant: Rails sharding and activerecord-tenanted
Rails added horizontal sharding in 6.1: shards with the same schema are declared in database.yml and attached with connects_to shards:, and code runs inside connected_to(role: :writing, shard: :acme). Since Rails 7.1 a ShardSelector middleware picks the shard per request from a resolver you supply, and its lock: true option prevents application code from switching tenant mid-request. The Rails guide on multiple databases recommends keeping that lock on for tenant-based sharding. This works well for a fixed list of shards, each holding many tenants; it was not designed to open thousands of databases on demand.
That gap is what activerecord-tenanted (0.9.0, October 2026, MIT), from 37signals, fills. It creates a connection pool per tenant on demand on top of Rails sharding, and points the primary database at a path such as storage/production/%{tenant}/main.sqlite3. It also patches the parts of Rails that a tenant can leak through: fragment caching, Active Job, Action Cable, Active Storage and Global ID. Only SQLite is fully supported, and the version number says what it is: young, opinionated, and best suited to new apps already committed to SQLite in production.
What every approach must handle
- Background jobs. A job runs outside the request, so the tenant must travel with it. acts_as_tenant stores it in Active Job arguments and ships an optional Sidekiq middleware; with schemas or databases, wrap the job's work in the gem's switch block. See our guide to background jobs in Rails for the queue side.
- Caches and file storage. Cache keys and Active Storage paths are global by default; include the tenant in keys and prefixes unless your gem does it for you.
- Uniqueness. A unique index on
emailis global in a shared table; it usually needs to be on[account_id, email]. The same applies to slugs, and to records hidden by a soft-delete gem, whose default scope interacts with the tenant scope. - Tests. Set and clear the tenant around every example. acts_as_tenant provides
test_tenantand a middleware for request specs, and warns that jobs performed inline reset the current tenant afterwards. Our testing guide covers the frameworks.
Which one
| Option | Isolation | Status, November 2026 | Best for |
|---|---|---|---|
| acts_as_tenant | Tenant column, enforced by the application | 2.2.2, October 2026; Rails 6.0+ | Most SaaS apps, many tenants, cross-tenant reporting |
| ros-apartment | PostgreSQL schema or database per tenant | 3.4.4 stable, May 2026; 4.0 in alpha | Tens to hundreds of large tenants, retrofitting a single-tenant app |
| Rails sharding | Database per shard | Built in since 6.1; ShardSelector since 7.1 | A fixed set of shards, each with many tenants |
| activerecord-tenanted | Database (SQLite file) per tenant | 0.9.0, October 2026 | New SQLite-first apps wanting strict isolation |
For a new app, start with acts_as_tenant and require_tenant switched on, and add PostgreSQL row-level security if a leak would be catastrophic. It is far easier to move a few large customers out to their own database later than to merge hundreds of schemas back together. Whatever you choose, run it through our gem evaluation checklist: tenancy code sits under every query in the app.
Category guidesBackground jobs
How to choose a background job backend for Rails: Active Job, Solid Queue (the Rails 8 default), Sidekiq, GoodJob, delayed_job and Resque, and what replaced Workling and Spawn.
Category guidesTesting
The Rails testing toolbox in 2026: Minitest or RSpec, fixtures or FactoryBot, system tests with Capybara, shoulda-matchers, and what replaced Webrat, Spork and factory_girl.
Category guidesSoft deletes
Discard adds a discarded_at column and two scopes; Paranoia and acts_as_paranoid override destroy. Which one, and when to skip soft deletes entirely.