Ruby
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Methods and Blocks
-
Section 4: Object-Oriented Ruby
-
Section 5: Metaprogramming
-
Section 6: Working with Data and Files
-
Section 7: Ruby Frameworks Overview
-
Section 8: Ecosystem and Testing
-
Section 9: Practical Projects
-
Section 10: Interview Practice
-
Section 11: Data Structures and Algorithms in Ruby
-
Section 12: More Practice Exercises
-
Section 13: Enumerable and Functional Style
-
Section 14: More OOP Practice
-
Section 15: More Testing
-
Section 16: Enumerable and Comparable Modules In Depth
-
Section 17: Ruby Standard Library: Core Utilities
-
Section 18: Ruby Standard Library: Data and Security
-
Section 19: Ruby Standard Library: CLI and Text
-
Section 20: Ruby Networking
-
Section 21: Ruby on Rails Deep Dive
-
Section 22: Ruby Metaprogramming Deep Dive
-
Section 23: Ruby Design Patterns
-
Section 24: Ruby Concurrency
-
Section 25: Ruby Testing Deep Dive
-
Section 26: Ruby Gems and Packaging
-
Section 27: Ruby Performance
-
Section 28: More Practice Exercises
-
Section 29: More Interview Practice
-
Section 30: Rails API Development
-
Section 31: Rails Authentication and Authorization
-
Section 32: Rails Testing Deep Dive
-
Section 33: Rails Performance
-
Section 34: Rails Deployment
-
Section 35: Sinatra and Lightweight Ruby Web Apps
-
Section 36: More Ruby Language Deep Dive
-
Section 37: Ruby 3.x Modern Features
-
Section 38: More Data Structures in Ruby
-
Section 39: More Practical Projects
-
Section 40: Ruby Ecosystem Tools
-
Section 41: More Practice and Review
-
Section 42: Final Practice and Mastery
-
Section 43: Ruby Interview Deep Dive
-
Section 44: Ruby Background Processing Deep Dive
-
Section 45: Ruby GraphQL
-
Section 46: Ruby Object Model Deep Dive
-
Section 47: Ruby Hanami Framework Overview
-
Section 48: Ruby gRPC and Protocol Buffers
-
Section 49: Ruby Data Processing
-
Section 50: Ruby Search Integration
-
Section 51: Ruby File Upload and Media
-
Section 52: Ruby Email and Notifications
-
Section 53: Ruby Admin Panels
-
Section 54: Ruby Feature Flags and Experimentation
-
Section 55: Ruby Monitoring and Observability
-
Section 56: Ruby Docker and Deployment Deep Dive
-
Section 57: Ruby Security Deep Dive
-
Section 58: More Advanced Metaprogramming
-
Section 59: More Final Projects
165: Building a Multi-Tenant SaaS with Rails
Imagine you're running a high-end apartment complex. You have one massive building (your application) and one plumbing system (your database). Every tenant has their own unit, their own furniture, and their own private life. Even though they all live under one roof and share the same foundation, the tenant in 4A should never accidentally walk into 4B and start rearranging the furniture. The walls are what provide that isolation. If a wall fails, you've got a massive privacy breach.
In a multi-tenant SaaS, your "building" is your Rails app, and your "apartments" are your customers. The "walls" are the logic you implement to ensure that when a user from Company A logs in, they can't see a single row of data belonging to Company B. If you forget a where(company_id: current_company.id) in just one controller action, you've effectively knocked down a wall and let a stranger into a customer's private living room.
Identifying the Tenant from the Request
First, we need to figure out who is knocking on the door. The most common way to do this in SaaS is via subdomains (e.g., apple.yourtool.com vs microsoft.yourtool.com). I prefer this over a simple dropdown menu because it feels more professional and makes session management cleaner.
To handle this without repeating yourself in every controller, we use a Current object. Rails provides ActiveSupport::CurrentAttributes for exactly this purpose—it's a thread-isolated way to store the current tenant so it's accessible anywhere in your app without passing variables through every single method.
# app/models/current.rb
class Current < ActiveSupport::CurrentAttributes
attribute :tenant
end
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
before_action :set_tenant
private
def set_tenant
# We look up the company based on the subdomain of the request
subdomain = request.subdomains.first
Current.tenant = Company.find_by!(subdomain: subdomain)
rescue ActiveRecord::RecordNotFound
render plain: "Company not found", status: :not_found
end
end
Building the Walls with Row-Level Isolation
Now that we know who the tenant is, we have to enforce the isolation. You could manually add .where(company_id: Current.tenant.id) to every query, but let's be honest: you'll forget it eventually. I've seen senior devs do it. It's a ticking time bomb.
Instead, we want a pattern that makes isolation the default. While some people use default_scope, I generally advise against it because it's a pain to bypass when you're writing admin scripts. A better approach is to create a concern that handles the scoping for you.
# app/models/concerns/tenantable.rb
module Tenantable
extend ActiveSupport::Concern
included do
belongs_to :company
# This ensures that whenever we create a record,
# it's automatically linked to the current tenant.
before_validation :set_company, on: :create
end
class_methods do
def for_current_tenant
where(company_id: Current.tenant.id)
end
end
private
def set_company
self.company_id ||= Current.tenant&.id
end
end
# Now apply it to your models
class Project < ApplicationRecord
include Tenantable
end
class Task < ApplicationRecord
include Tenantable
end
Now, in your controllers, instead of querying Project.all, you use Project.for_current_tenant. It's a small mental shift, but it makes it explicit that you are operating within a tenant's boundary.
Handling the "Cross-Tenant" Leak
Here is where things get tricky. What happens when you, the super-admin, need to see all projects across all companies to run a report? If you've locked everything down too tightly, you're stuck. This is why I advocate for the for_current_tenant method over a hard-coded default_scope. When you're in your admin dashboard, you simply call Project.all, and you have the full picture without fighting the framework.
One last tip: always add a database-level constraint. If you're using PostgreSQL, adding a NOT NULL constraint on company_id ensures that no "orphan" data ever exists in your system. Orphan data is the SaaS equivalent of a ghost in the machine—it's data that doesn't belong to anyone, but still takes up space and potentially leaks into searches.
📋 Practical Task
Exercise: Implementing a Tenant-Isolated Project Tracker
You are tasked with adding multi-tenancy to an existing Project Tracker application. The app currently allows any user to see any project, which is a major security flaw.
Your requirements:
- Create a
Companymodel with asubdomainstring column. - Implement a
Currentattributes class to hold the current tenant. - Implement a
Tenantableconcern that adds abelongs_to :companyrelationship and afor_current_tenantclass method. - Update the
Projectmodel to include theTenantableconcern. - Modify the
ProjectsController#indexaction so it only returns projects belonging to the company identified by the request's subdomain. - Ensure that when a new
Projectis created, it is automatically assigned to theCurrent.tenant.
There are no comments for now.