Created
December 7, 2012 18:09
-
-
Save adamrobbie/4235157 to your computer and use it in GitHub Desktop.
Heroku Secondary DB connection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 | |
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 | |
) | |
end | |
class SecondaryMigration < ActiveRecord::Migration | |
def connection | |
ActiveRecord::Secondary.connection | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment