Skip to content

Issue: Configuring Active Record to Use Different Base Classes for Sharded and Non-Sharded Models #1764

@rishav-enigma

Description

@rishav-enigma

Background
In our legacy Rails application, we have been using the active_record_shards gem to handle database sharding. Prior to upgrading to Rails 7.2, we patched certain models (e.g., Doorkeeper models) using not_sharded, ensuring they always connected to the primary database:

Doorkeeper::Application.class_eval do
  not_sharded
  ...
end

With the upgrade, we introduced two base classes to handle this explicitly:

class GlobalRecord < ActiveRecord::Base
  self.abstract_class = true
  connects_to database: { writing: :primary }
end
class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true
  ...
  # Defaults to shards
end

Problem
Instead of manually replacing every model’s superclass (e.g., Doorkeeper::Application < GlobalRecord), we are looking for a configuration-based solution that allows certain models to automatically connect to the primary database while keeping the rest on sharded connections.

Is there a recommended approach in Rails 7.2 to handle this use case without modifying every model explicitly?

Expected Behavior
A way to configure specific models (e.g., Doorkeeper::Application) to always use GlobalRecord or connect to :primary without manually changing every occurrence.
Ideally, this would be a simple Active Record configuration instead of modifying all model definitions.
Any guidance or best practices for handling this in Rails 7.2 would be greatly appreciated.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions