198
182

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Rails]複数のデータベースに接続する

Posted at

ひとつのMySQLサーバーだけでなく、もうひとつ別のMySQLサーバーに接続したい欲張りさんのための方法。

database.yml
development:
  # ひとつめはいつもどおり
  adapter: mysql2
  encoding: utf8
  database: database1
  username: hoge
  password: hogehoge
  host: database1.url
  port: 3306
  pool: 5
  timeout: 5000

test:
  # 略
production:
  # 略

# ふたつめ
database2:
  adapter: mysql2
  encoding: utf8
  database: database2
  username: fuga
  password: fugafuga
  host: database2.url
  port: 3306
  pool: 5
  timeout: 5000

modelを作成し、establish_connectionの引数にdatabase.ymlに追加した設定を指定する

futatsume.rb
class Futatsume < ActiveRecord::Base
  establish_connection(:database2)
end

ここまでできればあとはcontrollerから同じ使い方ができる

test_controller.rb
def test
  @futatsume = Futatsume.where(["name = ?", "test"])
end

しかししかし、
modelひとつひとつにestablish_connectionでデータベースを指定すると、
model毎にコネクションをはるっぽいので、DB接続コネクション数が異常に増えることになる。
なので、こうするのがベター

futatsume.rb
class Futatsume < ActiveRecord::Base
  establish_connection(:database2)
end
futasume_user.rb
class FutatsumeUser < Futatsume
end
futasume_task.rb
class FutasumeTask < Futasume
end

もとのFutatsumeクラスを継承するかたちに実装する。
使い方は同じ

test_controller.rb
def test
  @futatsume_user = FutatsumeUser.where(["name = ?", "test"])
  @futasume_tasks = FutatsumeUser.where(["id > ?", 10])
end
198
182
1

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
198
182

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?