diff --git a/app/models/tenant.rb b/app/models/tenant.rb index 52803ed9c..ed810c223 100644 --- a/app/models/tenant.rb +++ b/app/models/tenant.rb @@ -172,9 +172,21 @@ class Tenant < ApplicationRecord ActiveRecord::Base.connection.execute( "ALTER SCHEMA \"#{schema_before_last_save}\" RENAME TO \"#{schema}\";" ) + + rename_storage end end + def rename_storage + return unless ActiveStorage::Blob.service.is_a?(ActiveStorage::Service::TenantDiskService) + + old_storage = File.join(ActiveStorage::Blob.service.root, "tenants", schema_before_last_save) + return unless File.directory?(old_storage) + + new_storage = File.join(ActiveStorage::Blob.service.root, "tenants", schema) + File.rename(old_storage, new_storage) + end + def destroy_schema Apartment::Tenant.drop(schema) end diff --git a/spec/models/tenant_spec.rb b/spec/models/tenant_spec.rb index 1e7cda5a7..ca6be56be 100644 --- a/spec/models/tenant_spec.rb +++ b/spec/models/tenant_spec.rb @@ -1,4 +1,5 @@ require "rails_helper" +require "active_storage/service/disk_service" describe Tenant do describe ".resolve_host" do @@ -418,6 +419,48 @@ describe Tenant do end end + describe "#rename_storage" do + after do + FileUtils.rm_rf(File.join(ActiveStorage::Blob.service.root, "tenants", "notypo")) + end + + it "does nothing when the active storage blob service is not a TenantDiskService" do + disk_service = ActiveStorage::Service::DiskService.new(root: ActiveStorage::Blob.service.root) + allow(ActiveStorage::Blob).to receive(:service).and_return(disk_service) + tenant = create(:tenant, schema: "typo") + + expect(File).not_to receive(:rename) + + tenant.update!(schema: "notypo") + end + + it "does nothing when the tenant has no files to move" do + tenant = create(:tenant, schema: "typo") + + expect(File).not_to receive(:rename) + + tenant.update!(schema: "notypo") + end + + it "renames the active storage folder when updating the schema" do + tenant = create(:tenant, schema: "typo") + Tenant.switch("typo") do + Setting.reset_defaults + create(:image) + end + + expect(File).to receive(:rename).and_call_original + + tenant.update!(schema: "notypo") + + Tenant.switch("notypo") do + image = Image.first + expect(image.file_path).to include "/notypo/" + expect(File.exist?(image.file_path)).to be true + end + end + end + describe "#destroy_schema" do it "drops the schema when destroying a record" do tenant = create(:tenant, schema: "wrong")