我有两个结构相同的数据库。这些表有一个整数作为 Rails 中使用的主键。
如果我有一个患者表,我将让一名患者在一个数据库中使用主键 123,而另一名患者在另一个数据库中使用相同的主键。
对于合并来自两个数据库的数据,您有什么建议?
我有两个结构相同的数据库。这些表有一个整数作为 Rails 中使用的主键。
如果我有一个患者表,我将让一名患者在一个数据库中使用主键 123,而另一名患者在另一个数据库中使用相同的主键。
对于合并来自两个数据库的数据,您有什么建议?
使用 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
YMMV 取决于记录的数量和模型之间的关联。
如果您的数据库完全相同(数据不需要自定义处理)并且记录不多,您可以这样做(允许外键):
未经测试...但你明白了
#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
如果您有很多记录,则可能必须以某种方式将其分配出去……以 10k 为一组进行。
顺便说一句,将其作为 rake 或 capistrano 任务而不是迁移可能更有意义。