LoginSignup
1
1

More than 3 years have passed since last update.

Rails 3-5 複数のデータベースに接続する方法

Last updated at Posted at 2019-08-05

Rails 6 からは複数データベースが標準でサポートされた形になります(専用の書き方が決まっています)。
Rails 3-5 では次のようにすると、複数データベースを扱えます。

Config

データベースの設定をまず書きます。
基本的に database.yml に書けばOKで、 どんな名前でもOKです。

環境ごとの複数データベースを使うには、下のように複数のデータベースを記述します。

config/database.yml

development:
  ...

development_sub:
  ...

production:
  ...

production_sub:
  ...

抽象クラス作成

抽象クラスを作成して、追加されたデータベースを使う場合の基底クラスを作成します。

通常 Rails のモデルは ApplicationRecord を継承して "development" や "production" として設定されたデータベースを使うことになります。
作成する抽象クラスでは、 Rails.env に応じて接続先のデータベースを決定するようにします。

SubBase
class SubBase < ApplicationRecord
  self.abstract_class = true

  environment = Rails.env + "_sub"
  establish_connection(environment.to_sym)
end

使い方

ApplicationRecord を継承して従来通りのモデルの作り方をすると、 "development" や "production" に記述したデータベースを使用できます。
SubBase を継承してモデルを作成すると、 "development_sub", "production_sub" に記述したデータベースを使用できます。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1