secondbase
secondbase copied to clipboard
Accessing both databases in migrations
I'm trying to access both databases in a secondbase migration to transfer data between the two. Unfortunately, ActiveRecord::Base.connection is pointing at the same connection as SecondBase::Base.connection. Thoughts on how I would do that?
What does your database config look like?
This is the rough structure.
development:
test:
production:
second_base:
development:
test:
production:
I have it working with something like the following in my migration class.
class PrimaryServerBase < ActiveRecord::Base
self.abstract_class = true
establish_connection Rails.application.config.database_configuration[Rails.env]
end
class PrimaryServerModel < PrimaryServerBase
end
Any reasons that would be a bad idea?
@aaricpittman That looks perfectly fine. Even when an application has one database and doing some ETL in a migration, I always declare a local model in the migration to isolate behavior. In your case you have a need to talk to two models that spans DBs and hence you would need to use establish_connection like you are doing above.
The only issue I can think of is declaring an explicit second transaction. But that is only important if you are writing to both DBs during the migration. If your PrimaryServerBase
connection is read-only and you are writing to Secondbase - you are already guaranteed a transaction due to the current migration. If not, just open a transaction block on your other model. Sound good?