How to use multiple databases for one rails 3.1 app in Heroku?

前端 未结 3 833
忘掉有多难
忘掉有多难 2020-12-15 08:53

My Rails 3.1 application connects to 2 databases, one is the default, the other is an Amazon RDS MYSQL instance.

The current database.yml contains two production dat

3条回答
  •  囚心锁ツ
    2020-12-15 09:10

    Working off of the previous responses, but incorporating some Rails 3 advantages with the configuration and simplifying the parsing...

    # config/application.rb
    module MyApp
      class Application < Rails::Application
        ... other configs
    
        config.secondary_database_url = ENV['SECONDARY_DB_URL']
      end
    end
    

    We may want to override this in development / test

    # config/environments/development.rb
    
    module MyApp
      class Application < Rails::Application
        ... other configs
    
        config.secondary_database_url = 'SOME_CONNECTION_STRING'
      end
    end    
    

    Now to setup the class we'll have our models inherit from...

    # 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
    

提交回复
热议问题