method

connected_to

Importance_2
v7.1.3.2 - Show latest stable - 0 notes - Class: ConnectionHandling
connected_to(role: nil, shard: nil, prevent_writes: false, &blk) public

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
Show source
Register or log in to add new notes.