从 Rails 连接到远程数据库只是为了提取一些数据的最佳方法是什么?我需要在远程服务器上执行查询并检索列值。这些列将本地存储在模型中。
谢谢!
最佳答案
对于多数据库连接,需要在database.yml文件中添加如下代码。
配置/数据库.yml
other_db:
adapter: mysql2
database: db1_dev
username: root
password: xyz
host: localhost
然后创建一个新模型。
class ImportLine < ActiveRecord::Base
establish_connection "other_db"
self.table_name = "the_table_in_th_other_db"
end
现在您可以像这样选择任意列:
ImportLine.select(:col1, :col2).find_each do |line|
puts "#{line.col1} -#{line.col1}"
end
关于ruby-on-rails - Rails 在没有模型的情况下连接到远程数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32092097/