establish_connection
データベースと接続するためのメソッド。
通常は明示的に呼び出すことはない。
しかし、
複数のデータベースを使用し、モデルごとに接続先DBが異なる場合は、クラス定義の内側で明示的に呼び出す必要がある。
一般的には、database.ymlに接続先DB情報を記載しておき、シンボルとして参照する。
database.yml
***:
adapter: ...
database: other_database
pool: 5
username: USERNAME
password: PASSWORD
host: localhost
models/~~.rb
establish_connection :***
DBの接続情報はサブクラスへ引き継がれる
ActiveRecord::Railtieのinitializerを上書き
Rails上でActiveRecordを使うと config/database.yml
を読み取ってよしなに establish_connection
をしてくれるが、
そのへんの処理を自分で定義したい場合、Railtieの initializer を上書きする必要がある。
/vendor/bundle/ruby/2.5.0/gems/activerecord-5.2.1/lib/active_record/railtie.rb
# This sets the database configuration from Configuration#database_configuration
# and then establishes the connection.
initializer "active_record.initialize_database" do
ActiveSupport.on_load(:active_record) do
self.configurations = Rails.application.config.database_configuration
begin
establish_connection
rescue ActiveRecord::NoDatabaseError
warn <<-end_warning
Oops - You have a database configured, but it doesn't exist yet!
Here's how to get started:
1. Configure your database in config/database.yml.
2. Run `bin/rails db:create` to create the database.
3. Run `bin/rails db:setup` to load your database schema.
end_warning
raise
end
end
end