针对多个数据库执行原始 SQL

Kyb*_*b3r 2 sql-server sqlite activerecord ruby-on-rails

这是执行原始 sql的后续操作 。我正在开发一个项目,需要从多个数据库中传输信息。我会怎么做类似的事情

sql = "Select * from ... your sql query here"
records_array = ActiveRecord::Base.connection.execute(sql)
Run Code Online (Sandbox Code Playgroud)

但支持选择连接?

Ily*_*rov 5

您可以使用ActiveRecord::Base.establish_connection切换数据库连接。代码应该是这样的:

#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)
Run Code Online (Sandbox Code Playgroud)

establish_connection您可以在Rails 文档中找到有关详细信息。