ActiveStorage Multi DB support

At my work we are have a use case for ActiveStorage to be backed by multiple attachment / blob tables across separate DBs. Our specific use case is that we are about to move to deploying our Rails application regionally to respect data sovereignty requirements. Our plan is to utilise Rails multi-DB support to point models that store user generated data to regional DBs, while pointing all other models to a single global DB. Since we have both global and regional models with attachments, we need ActiveStorage tables in both databases if we are to respect customer data sovereignty and not have missing assets across regions.

As noted by @georgeclaghorn in a Rails GH issue:

If you want Active Storage to look in different DBs for attachments to different records, that’s probably going to require framework support.

So here I am, requesting the feature! We only need this at a model level though, not record. I can imagine this working something like this:

# My custom AS models
class Global::Blob < ActiveStorage::Blob
  connects_to(database: { writing: :global, reading: :global })
end
class Global::VariantRecord < ActiveStorage::VariantRecord
  connects_to(database: { writing: :global, reading: :global })
end
class Global::Attachment < ActiveStorage::Attachment
  blob_class Global::Blob 
  variant_class Global::VariantRecord
  connects_to(database: { writing: :global, reading: :global })
end

# I am a regular "regional" model
class User < ApplicationRecord
  # just uses ActiveStorage::Attachment, which uses the default regional DB
  has_one_attached :picture
end

# I am a global model
class BlogPost < ApplicationRecord
  connects_to :global
  # This is how I explicitly override a class to use a different 
  has_one_attached :picture, class: Global::Attachment
end

But I have no strong opinions there, just looking to see if this is a feature Rails would consider adopting? We are happy to contribute to the implementation. It would be my/our first Rails contribution, so guidance on how to approach it would be very much appreciated.

Thanks,

Matt

2 Likes