instance method
connects_to
Ruby on Rails 7.1.6
Since v6.0.6Signature
connects_to(database: {}, shards: {})
Connects a model to the databases specified. The database keyword takes a hash consisting of a role and a database_key.
This will look up the database config using the database_key and establish a connection to that config.
class AnimalsModel < ApplicationRecord self.abstract_class = true connects_to database: { writing: :primary, reading: :primary_replica } end
connects_to also supports horizontal sharding. The horizontal sharding API supports read replicas as well. You can connect a model to a list of shards like this:
class AnimalsModel < ApplicationRecord self.abstract_class = true connects_to shards: { default: { writing: :primary, reading: :primary_replica }, shard_two: { writing: :primary_shard_two, reading: :primary_shard_replica_two } } end
Returns an array of database connections.
Parameters
-
databasekey = {} -
shardskey = {}
Source
# File activerecord/lib/active_record/connection_handling.rb, line 81
def connects_to(database: {}, shards: {})
raise NotImplementedError, "`connects_to` can only be called on ActiveRecord::Base or abstract classes" unless self == Base || abstract_class?
if database.present? && shards.present?
raise ArgumentError, "`connects_to` can only accept a `database` or `shards` argument, but not both arguments."
end
connections = []
if shards.empty?
shards[:default] = database
end
self.default_shard = shards.keys.first
shards.each do |shard, database_keys|
database_keys.each do |role, database_key|
db_config = resolve_config_for_connection(database_key)
self.connection_class = true
connections << connection_handler.establish_connection(db_config, owner_name: self, role: role, shard: shard.to_sym)
end
end
connections
end
Defined in activerecord/lib/active_record/connection_handling.rb line 81
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActiveRecord::ConnectionHandling