nbudin / heroku_external_db

Makes it easy to connect to external databases from a Heroku app
MIT License
40 stars 5 forks source link

Config Connections #5

Closed lusabo closed 13 years ago

lusabo commented 13 years ago

Hi,

I have an application running on Heroku using postgresql. I would like to add an external database (mysql or postgresql) to maintain tables with images. How to configure to add the additional database but not make it the main?

I've copied the initializer.

Thanks, Luciano

nbudin commented 13 years ago

I use a similar setup to keep an external database of user accounts. Here is what I use:

if ENV['EXTERNAL_DATABASE_URL']
  HerokuExternalDb.setup_configuration!("USERS", "users")
  HerokuExternalDb.setup_rails_env!
end

Then, in the models that should use the external database:

establish_connection :users

The way this works is by setting up a separate Rails environment for users. So in this example, you'd also want to add a section in database.yml for a separate users database.

Note that doing this can create issues! You won't be able to create assocations (has_one, belongs_to, etc) between models in different databases. So you will have to handle the finds yourself, probably by reading the IDs from the appropriate records.

In fact, it's enough of a pain that I am currently in the process of migrating from a separate database of users to instead using a CAS server. Similarly, I would recommend that you seriously consider the implications of a multi-database setup in ActiveRecord before you decide to proceed.

nbudin commented 13 years ago

Forgot to add above: the environment variable ends up being USERS_DATABASE_URL for the users database.