Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
846 views
in Technique[技术] by (71.8m points)

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

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 database connections. The models that need to pull from the second database simply use

establish_connection "production_on_amazon"

Unfortunately Heroku overwrites your database.yml, and only seems to inlcude one database connection. Does anyone know how I can add or configure my second?

Running "heroku config" I can see there are 2 DB's listed but cant seem to configure to connect to both. Perhaps somehow set my default to the SHARED_DATABASE_URL db on Heroku and set the alternate to the DATABASE_URL which points to Amazon...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...