2

This is a followup to executing raw sql. I am working on a project where I need to stream in information form multiple databases. How would I do something similar to

sql = "Select * from ... your sql query here"
records_array = ActiveRecord::Base.connection.execute(sql)

but have support for choosing the connection??

Community
  • 1
  • 1
Kyb3r
  • 49
  • 7

1 Answers1

5

You may use ActiveRecord::Base.establish_connection to switch database connection. Code should be like this:

#database.yml
development:
  adapter: postgresql
  host: 127.0.0.1
  username: postgres
  password: postgres
  database: development_db

development_another_db:
  adapter: postgresql
  host: 127.0.0.1
  username: postgres
  password: postgres
  database: another_db


ActiveRecord::Base.establish_connection :development_another_db
sql = "Select * from ... your sql query here"
records_array = ActiveRecord::Base.connection.execute(sql)

ActiveRecord::Base.establish_connection :development
sql = "Another select"
records_array = ActiveRecord::Base.connection.execute(sql)

You may find details about establish_connection in Rails documentation.

Ilya Lavrov
  • 2,810
  • 3
  • 20
  • 37