2017-03-22 64 views
0

这是 executing raw sql的后续处理。我正在开发一个项目,我需要从多个数据库中传输信息。我该怎么办类似于对多个数据库执行原始数据库

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

但支持选择连接?

回答

0

您可以使用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) 

您可能会发现有关Rails documentationestablish_connection细节。