class Document < ApplicationRecord
belongs_to :owner, class_name: "User"
has_many :visibilities, class_name: "DocumentVisibility", dependent: :delete_all
scope :public_documents, -> { where(is_public: true) }
-- Pattern 1: Shared schema with tenant_id column
CREATE TABLE tenants (
id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL,
slug VARCHAR(50) UNIQUE NOT NULL,
Apartment.configure do |config|
config.excluded_models = %w[Tenant User]
config.tenant_names = -> { Tenant.pluck(:schema_name) }
config.use_schemas = true
end
<?php
namespace App\Scopes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
class Comment < ApplicationRecord
belongs_to :account
belongs_to :author, class_name: "User"
validates :body, presence: true
import threading
from contextlib import contextmanager
_state = threading.local()
<?php
namespace App\Models\Scopes;
use App\Support\TenantContext;
use Illuminate\Database\Eloquent\Builder;
class Current < ActiveSupport::CurrentAttributes
attribute :tenant, :request_id
def tenant=(tenant)
super
Rails.logger.tagged("tenant=#{tenant&.id}") if tenant
package com.example.demo.multitenancy;
public class TenantContext {
private static final ThreadLocal<String> CURRENT_TENANT = new ThreadLocal<>();
public static void setTenantId(String tenantId) {