连接到另一个数据库适配器

时间:2013-04-17 21:21:12

标签: ruby-on-rails ruby

我正在尝试将一些旧的mysql数据导入到我的网站的postgresql数据库中,但是我在连接到旧的mysql数据库时遇到了一些麻烦。我创建了一个rake任务来尝试从我的旧数据库中打印用户名,但我似乎无法弄明白。这就是我想要做的事情:

desc "imports old records to the new postgresql db"
task "db:import_old" => :environment do

  class OldDatabase < ActiveRecord::Base
    self.establish_connection(
      :adapter  => "mysql2",
      :host     => "localhost",
      :username => "root",
      :password => "",
      :database => "old_database"
    )
  end

  user = OldDatabase.user.find_by_user_id(1)

  puts "Hello, #{user.name}!"
  puts
end

但我永远无法输出旧数据库的数据。有什么建议?谢谢! :)

1 个答案:

答案 0 :(得分:1)

通常,您希望为每个底层数据库定义一个类,继承自ActiveRecord,然后修改连接参数。

然后,在你的模型中,你将继承这些专门的类,而不是从ActiveRecord :: Base

继承
 class DatabaseCurrent < ActiveRecord::Base
   self.abstract_class = true
   establish_connection settings['database']
 end

 class DatabaseOld < ActiveRecord::Base
   self.abstract_class = true
   establish_connection settings['database2']
 end

 # in your Model definitions:

 class User < DatabaseCurrent
 #...
 end

 class OldUser < DatabaseOld
 # ... 
 end

使用Rails:

http://blog.vishnugopal.com/2008/01/12/multiple-db-connections-in-railsactiverecord/

没有Rails:

http://idevone.wordpress.com/2010/09/26/multiple-activerecord-connections-without-rails/