ruby 34 lines · 3 tabs

Multi-tenancy with apartment gem

Alex Kumar Jan 2026
3 tabs
Apartment.configure do |config|
  config.excluded_models = %w[Tenant User]
  config.tenant_names = -> { Tenant.pluck(:schema_name) }
  config.use_schemas = true
end

Rails.application.config.middleware.use Apartment::Elevators::Subdomain
3 files · ruby Explain with highlit

SaaS applications serving multiple customers (tenants) need data isolation to prevent cross-tenant data leaks. The apartment gem provides schema-based multi-tenancy for PostgreSQL where each tenant gets a separate schema, ensuring complete database-level isolation. Tenant switching happens via Apartment::Tenant.switch(tenant_name), typically in a middleware or controller concern that extracts the tenant from subdomain or request headers. Migrations run across all tenant schemas automatically. This approach provides strong isolation with reasonable performance overhead. The alternative—row-based tenancy with a tenant_id column—is simpler but requires perfect discipline in all queries to avoid accidental cross-tenant data exposure. Schema-based tenancy makes mistakes obvious.


Related snips

Share this code

Here's the card — post it anywhere.

Multi-tenancy with apartment gem — share card
Link copied