instance method
connected_to_many
Ruby on Rails edge
Since v6.1.7.10Signature
connected_to_many(*classes, role:, shard: nil, prevent_writes: role == ActiveRecord.reading_role)
Connects a role and optionally shard to the provided connection names. The prevent_writes option can be passed to block writes on a connection; it defaults to true when using the reading role.
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
-
classesrest -
rolekeyreq -
shardkey = nil -
prevent_writeskey = role == ActiveRecord.reading_role
Source
# File activerecord/lib/active_record/connection_handling.rb, line 173
def connected_to_many(*classes, role:, shard: nil, prevent_writes: role == ActiveRecord.reading_role)
classes = classes.flatten
if self != Base || classes.include?(Base)
raise NotImplementedError, "connected_to_many can only be called on ActiveRecord::Base."
end
if role == ActiveRecord.reading_role && !prevent_writes
raise ArgumentError, "cannot set `prevent_writes` to false when `role` is `reading`."
end
append_to_connected_to_stack(role: role, shard: shard, prevent_writes: prevent_writes, klasses: classes)
begin
yield
ensure
connected_to_stack.pop
end
end
Defined in activerecord/lib/active_record/connection_handling.rb line 173
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActiveRecord::ConnectionHandling