Rails无需模型即可连接到远程数据库

时间:2015-08-19 09:50:24

标签: ruby-on-rails

从Rails连接到远程数据库只是为了提取一些数据的最佳方法是什么?我需要在远程服务器上执行查询并检索列值。这些列将存储在模型中的本地。

谢谢!

1 个答案:

答案 0 :(得分:7)

对于多数据库连接,您需要将以下代码添加到database.yml文件中。

配置/ database.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
相关问题