Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

Como usar vários bancos de dados para um aplicativo Rails 3.1 no Heroku?


Trabalhando com as respostas anteriores, mas incorporando algumas vantagens do Rails 3 com a configuração e simplificando a análise...
# config/application.rb
module MyApp
  class Application < Rails::Application
    ... other configs

    config.secondary_database_url = ENV['SECONDARY_DB_URL']
  end
end

Podemos querer substituir isso no desenvolvimento/teste
# config/environments/development.rb

module MyApp
  class Application < Rails::Application
    ... other configs

    config.secondary_database_url = 'SOME_CONNECTION_STRING'
  end
end    

Agora, para configurar a classe, teremos nossos modelos herdados de ...
# lib/active_record/secondary.rb 
module ActiveRecord
  class Secondary < ActiveRecord::Base
    self.abstract_class = true

    # prior to AR 3.2.1
    url = URI.parse( MyApp::Application.config.secondary_database_url )
    establish_connection(
      :adapter  => 'mysql',
      :host     => url.host,
      :username => url.userinfo.split(':')[0],
      :password => url.userinfo.split(':')[1],
      :database => url.path[1..-1],
      :port     => url.port || 3306
    )

    # as of AR 3.2.1
    establish_connection(MyApp::Application.config.secondary_database_url)

  end

  class SecondaryMigration < ActiveRecord::Migration
    def connection
      ActiveRecord::Secondary.connection 
    end
  end

end