instance method connected_to

Ruby on Rails 6.0.6

Since v6.0.6

Available in: v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

connected_to(database: nil, role: nil, prevent_writes: false, &blk)

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

The database kwarg is deprecated in 6.1 and will be removed in 6.2

It is not recommended for use as it re-establishes a connection every time it is called.

Parameters

database key = nil
role key = nil
prevent_writes key = false
blk block
Source
# File activerecord/lib/active_record/connection_handling.rb, line 103
    def connected_to(database: nil, role: nil, prevent_writes: false, &blk)
      if database && role
        raise ArgumentError, "connected_to can only accept a `database` or a `role` argument, but not both arguments."
      elsif database
        if database.is_a?(Hash)
          role, database = database.first
          role = role.to_sym
        end

        config_hash = resolve_config_for_connection(database)
        handler = lookup_connection_handler(role)

        handler.establish_connection(config_hash)

        with_handler(role, &blk)
      elsif role
        prevent_writes = true if role == reading_role

        with_handler(role.to_sym) do
          connection_handler.while_preventing_writes(prevent_writes, &blk)
        end
      else
        raise ArgumentError, "must provide a `database` or a `role`."
      end
    end

Defined in activerecord/lib/active_record/connection_handling.rb line 103 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveRecord::ConnectionHandling

Type at least 2 characters to search.

↑↓ navigate · open · esc close