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(database: nil, role: nil, &blk)
public
Connects to a database or role (ex writing, reading, or another custom role) for the duration of the block.
If a role is passed, Active Record will look up the connection based on the requested role:
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 ActiveRecord::Base.connected_to(role: :unknown_role) do # raises exception due to non-existent role end
For cases where you may want to connect to a database outside of the model, you can use connected_to with a database argument. The database argument expects a symbol that corresponds to the database key in your config.
ActiveRecord::Base.connected_to(database: :animals_slow_replica) do Dog.run_a_long_query # runs a long query while connected to the +animals_slow_replica+ end
This will connect to a new database for the queries inside the block. By default the `:writing` role will be used since all connections must be assigned a role. If you would like to use a different role you can pass a hash to database:
ActiveRecord::Base.connected_to(database: { readonly_slow: :animals_slow_replica }) do # runs a long query while connected to the +animals_slow_replica+ using the readonly_slow role. Dog.run_a_long_query end
When using the database key a new connection will be established every time.