instance method connected_to_many

Ruby on Rails 7.0.10

Since v6.1.7.10

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

Signature

connected_to_many(*classes, role:, shard: nil, prevent_writes: false)

Connects a role and/or shard to the provided connection names. Optionally prevent_writes can be passed to block writes on a connection. reading will automatically set prevent_writes to true.

connected_to_many is an alternative to deeply nested connected_to blocks.

Usage:

ActiveRecord::Base.connected_to_many(AnimalsRecord, MealsRecord, role: :reading) do
  Dog.first # Read from animals replica
  Dinner.first # Read from meals replica
  Person.first # Read from primary writer
end

Parameters

classes rest
role keyreq
shard key = nil
prevent_writes key = false
Source
# File activerecord/lib/active_record/connection_handling.rb, line 172
    def connected_to_many(*classes, role:, shard: nil, prevent_writes: false)
      classes = classes.flatten

      if ActiveRecord.legacy_connection_handling
        raise NotImplementedError, "connected_to_many is not available with legacy connection handling"
      end

      if self != Base || classes.include?(Base)
        raise NotImplementedError, "connected_to_many can only be called on ActiveRecord::Base."
      end

      prevent_writes = true if role == ActiveRecord.reading_role

      append_to_connected_to_stack(role: role, shard: shard, prevent_writes: prevent_writes, klasses: classes)
      yield
    ensure
      connected_to_stack.pop
    end

Defined in activerecord/lib/active_record/connection_handling.rb line 172 · 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