合并Rails数据库

hec*_*rsq 5 merge database-design ruby-on-rails

我有两个结构相同的数据库.这些表有一个整数作为Rails中使用的主键.

如果我有患者表,我将有一名患者在一个数据库中使用主键123,而另一名患者在另一个数据库中使用相同的主键.

您建议合并两个数据库中的数据?

小智 10

使用config/database.yml中的条目设置数据库,然后生成新的迁移.

使用ActiveRecord :: Base.establish_connection在迁移中的两个数据库之间切换,如下所示:

def self.up
  ActiveRecord::Base.establish_connection :development
  patients = Patient.find(:all)
  ActiveRecord::Base.establish_connection :production
  patients.each { |patient| Patient.create patient.attributes.except("id") }
end
Run Code Online (Sandbox Code Playgroud)

YMMV取决于记录的数量和模型之间的关联.


Dan*_*ley 5

如果您的数据库完全相同(数据不需要自定义处理)并且没有太多记录,您可以这样做(允许外键):

未经测试......但你明白了

#All models and their foreign keys
tales = {Patients => [:doctor_id, :hospital_id],
         Doctors => [:hospital_id],
         Hospitals}

ActiveRecord::Base.establish_connection :development

max_id = tables.map do |model|  
  model.maximum(:id)
end.max + 1000


tables.each do |model, fks|  
  ActiveRecord::Base.establish_connection :development
  records = model.find(:all)

  ActiveRecord::Base.establish_connection :production
  records.each do |record|
    #update the foreign keys
    fks.each do |attr|
      record[attr] += max_id if not record[attr].nil?
    end
    record.id += max_id

    model.create record.attributes
  end
end
Run Code Online (Sandbox Code Playgroud)

如果你有很多记录,你可能不得不以某种方式将它分开...以10k或其他的组进行.