ActiveRecord でモデルごとに別のデータベースを使う方法
2007/03/28
ある Rails アプリケーションで他の Rails アプリケーションのデータベースを参照したかったので、方法を調べました。情報源は以下のサイトです。
ActiveRecord の API ドキュメントにはこう書いてあります。
Connections are usually created through ActiveRecord::Base.establish_connection and retrieved by ActiveRecord::Base.connection. All classes inheriting from ActiveRecord::Base will use this connection. But you can also set a class-specific connection. For example, if Course is a ActiveRecord::Base, but resides in a different database you can just say Course.establish_connection and Course *and all its subclasses* will use this connection instead.
データベースへのコネクションは ActiveRecord::Base.establish_connection で作られるので、あるモデル(例えば Course)で別のコネクションを使いたければ、Course.establish_connection を自分で呼べばよいらしい。ということでやってみました。