Skip to content

Conversation

@flavorjones
Copy link
Member

to allow applications to extend tenant change behavior.

I'm using this functionality in my current project to cascade a second tenant change in another database, something like this:

module ApplicationRecordWithTenantZoneExtension
  extend ActiveSupport::Concern

  class_methods do
    def with_zone(&block)
      ZonedRecord.with_tenant(tenant_zone, &block)
    end

    def set_queue_zone
      ZonedRecord.current_tenant = tenant_zone
    end

    def tenant_zone
      # ... business logic to determine the "zone" for ApplicationRecord.current_tenant
    end
  end

  included do
    set_callback :with_tenant,        :around, :with_zone
    set_callback :set_current_tenant, :after,  :set_zone
  end
end

Rails.application.config.to_prepare do
  ApplicationRecord.include ApplicationRecordWithTenantZoneExtension
end

so that the application only needs to call ApplicationTenant.with_tenant and the tenant is automatically set on the secondary database as well.

to allow applications to extend tenant change behavior.
@flavorjones flavorjones enabled auto-merge November 9, 2025 17:55
@flavorjones flavorjones merged commit 1e92cb3 into main Nov 9, 2025
7 checks passed
@flavorjones flavorjones deleted the flavorjones/with-tenant-callbacks branch November 9, 2025 17:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants