2012/04/24

[rails]establish_connectionで接続先DBを変更する。

開発中の一連のシステムは、Rails3によるアプリを複数立ち上げ、 全て同じデータベースを参照している。
データベースは、その中の1つが管理(schemaや、migration)し、 他のアプリは、そのデータベースに接続する。

データベースを管理しないアプリ側では以下のコードを実装し、 接続先を変更する。
{Rails.root}/lib/custom_connection.rb

  module CustomConnection

    def establish_connection_to_other
      case Rails.env
      when "development"
        establish_connection :other_development
      when "test"
        establish_connection :other_test
      when "staging"
        establish_connection :other_staging
      when "production"
        establish_connection :other_production
      end
    end

  end
  ActiveRecord::Base.send(:extend, CustomConnection)

{Rails.root}/config/initializers/config.rb

  require 'custom_connection'
  ActiveRecord::Base.establish_connection_to_other

config/database.ymlには、 other_development, other_test, other_staging, other_productionの 定義が必要になる。

0 件のコメント: