1

我正在尝试将一些旧的 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

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

4

1 回答 1

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

使用导轨:

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

没有导轨:

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

于 2013-04-17T21:29:41.900 回答