Rails ActiveRecord将数据从旧数据库复制到新数据库

时间:2019-09-28 05:18:14

标签: ruby-on-rails activerecord

我必须将我的应用程序数据从旧的应用程序数据库移动到新的应用程序数据库。表结构不同。我已经编写了以下脚本。

require 'mysql2'
require 'active_record'

old_database = {
adapter:  "mysql2",
host:     "localhost",
username: "foo",
password: "bar",
database: "old_db",
socket: "/var/run/mysqld/mysqld.sock"
}

new_database = {
adapter:  "mysql2",
encoding: "utf8mb4",
collation: "utf8mb4_bin",
host:     "localhost",
username: "foo",
password: "bar",
database: "new_db",
socket: "/var/run/mysqld/mysqld.sock"
}

class Doctor < ActiveRecord::Base  
end

用于从旧数据库读取单个记录的代码

ActiveRecord::Base.establish_connection(old_database)
  doctor_attributes = Doctor.order(:id).limit(1).offset(offset).first.attributes
  ActiveRecord::Base.remove_connection

其后是用于使doctor_params与新表结构一致的代码。在新数据库中创建条目的代码如下。

ActiveRecord::Base.establish_connection(new_database)
Doctor.create(doctor_params)

问题是最后一行的Doctor对象具有旧数据库的属性。我不能正确处理数据库连接还是存在其他问题?

我尝试了以下

ActiveRecord::Base.establish_connection(old_db)
ActiveRecord::Base.establish_connection(new_db)
doctor = Doctor.new #Instance of doctor as per new database

但如果我这样做

ActiveRecord::Base.establish_connection(old_db)
doctor = Doctor.new # instance of doctor as per old database
ActiveRecord::Base.establish_connection(new_db)
doctor = Doctor.new # Still instance of doctor as per new database

Doctor模型以某种方式陷入旧数据库中。

2 个答案:

答案 0 :(得分:1)

我解决了以下问题

require 'mysql2'
require 'active_record'    

class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true
end

class Doctor < ApplicationRecord
  old_database = {
    adapter:  "mysql2",
    host:     "localhost",
    username: "foo",
    password: "bar",
    database: "old_db"
  }
  establish_connection(old_database)
end

class NewDoctor < ApplicationRecord
  new_database = {
    adapter:  "mysql2",
    encoding: "utf8mb4",
    collation: "utf8mb4_bin",
    host:     "localhost",
    username: "foo",
    password: "bar",
    database: "new_db",
    socket: "/var/run/mysqld/mysqld.sock"
  }
  self.table_name = 'doctors'
  establish_connection(new_database)
end

感觉很“ hackey”,我确信在处理大型数据库时效率不高,但是可以解决我的危机情况。我的数据库有大约8000个条目,因此我不担心效率问题。

答案 1 :(得分:0)

尝试

Doctor.establish_connection :new_database
Doctor.create doctor_params

使用

# config/database.yml

default: &default
  adapter: mysql2
  host: localhost
  username: foo
  password: bar
  socket: /var/run/mysqld/mysqld.sock

old_database:
  <<: *default
  database: old_db

new_database:
  <<: *default
  database: new_db
  encoding: utf8mb4
  collation: utf8mb4_bin