connected_to
- 1.0.0
- 1.1.6
- 1.2.6
- 2.0.3
- 2.1.0
- 2.2.1
- 2.3.8
- 3.0.0
- 3.0.9
- 3.1.0
- 3.2.1
- 3.2.8
- 3.2.13
- 4.0.2
- 4.1.8
- 4.2.1
- 4.2.7
- 4.2.9
- 5.0.0.1
- 5.1.7
- 5.2.3
- 6.0.0 (0)
- 6.1.3.1 (-38)
- 6.1.7.7 (1)
- 7.0.0 (-10)
- 7.1.3.2 (0)
- 7.1.3.4 (0)
- What's this?
connected_to(role: nil, shard: nil, prevent_writes: false, &blk)
public
Connects to a role (ex 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