instance method
connected_to
Ruby on Rails 7.2.3
Since v6.0.6Signature
connected_to(role: nil, shard: nil, prevent_writes: false, &blk)
Connects to a role (e.g. writing, reading, or a custom role) and/or shard for the duration of the block. At the end of the block the connection will be returned to the original role / shard.
If only a role is passed, Active Record will look up the connection based on the requested role. If a non-established role is requested an ActiveRecord::ConnectionNotEstablished error will be raised:
ActiveRecord::Base.connected_to(role: :writing) do Dog.create! # creates dog using dog writing connection end ActiveRecord::Base.connected_to(role: :reading) do Dog.create! # throws exception because we're on a replica end
When swapping to a shard, the role must be passed as well. If a non-existent shard is passed, an ActiveRecord::ConnectionNotEstablished error will be raised.
When a shard and role is passed, Active Record will first lookup the role, and then look up the connection by shard key.
ActiveRecord::Base.connected_to(role: :reading, shard: :shard_one_replica) do Dog.first # finds first Dog record stored on the shard one replica end
Parameters
-
rolekey = nil -
shardkey = nil -
prevent_writeskey = false -
blkblock
Source
# File activerecord/lib/active_record/connection_handling.rb, line 134
def connected_to(role: nil, shard: nil, prevent_writes: false, &blk)
if self != Base && !abstract_class
raise NotImplementedError, "calling `connected_to` is only allowed on ActiveRecord::Base or abstract classes."
end
if !connection_class? && !primary_class?
raise NotImplementedError, "calling `connected_to` is only allowed on the abstract class that established the connection."
end
unless role || shard
raise ArgumentError, "must provide a `shard` and/or `role`."
end
with_role_and_shard(role, shard, prevent_writes, &blk)
end
Defined in activerecord/lib/active_record/connection_handling.rb line 134
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActiveRecord::ConnectionHandling