instance method connects_to

Ruby on Rails 7.0.10

Since v6.0.6

Available in: v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

connects_to(database: {}, shards: {})

Connects a model to the databases specified. The database keyword takes a hash consisting of a role and a database_key.

This will create a connection handler for switching between connections, look up the config hash using the database_key and finally establishes a connection to that config.

class AnimalsModel < ApplicationRecord
  self.abstract_class = true

  connects_to database: { writing: :primary, reading: :primary_replica }
end

connects_to also supports horizontal sharding. The horizontal sharding API also supports read replicas. Connect a model to a list of shards like this:

class AnimalsModel < ApplicationRecord
  self.abstract_class = true

  connects_to shards: {
    default: { writing: :primary, reading: :primary_replica },
    shard_two: { writing: :primary_shard_two, reading: :primary_shard_replica_two }
  }
end

Returns an array of database connections.

Parameters

database key = {}
shards key = {}
Source
# File activerecord/lib/active_record/connection_handling.rb, line 81
    def connects_to(database: {}, shards: {})
      raise NotImplementedError, "`connects_to` can only be called on ActiveRecord::Base or abstract classes" unless self == Base || abstract_class?

      if database.present? && shards.present?
        raise ArgumentError, "`connects_to` can only accept a `database` or `shards` argument, but not both arguments."
      end

      connections = []

      database.each do |role, database_key|
        db_config, owner_name = resolve_config_for_connection(database_key)
        handler = lookup_connection_handler(role.to_sym)

        self.connection_class = true
        connections << handler.establish_connection(db_config, owner_name: owner_name, role: role)
      end

      shards.each do |shard, database_keys|
        database_keys.each do |role, database_key|
          db_config, owner_name = resolve_config_for_connection(database_key)
          handler = lookup_connection_handler(role.to_sym)

          self.connection_class = true
          connections << handler.establish_connection(db_config, owner_name: owner_name, role: role, shard: shard.to_sym)
        end
      end

      connections
    end

Defined in activerecord/lib/active_record/connection_handling.rb line 81 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveRecord::ConnectionHandling

Type at least 2 characters to search.

↑↓ navigate · open · esc close