I’m using a rake task to move data between databases with slightly different schemas.
This is no problem when the model names are different. For example copying information from a separate database with a “Manufacturer” model into the “Company” model of the current application:
task :copy_from_old_to_new => :environment do
require "active_record"
class Manufacturer < ActiveRecord::Base
end
Manufacturer.establish_connection(
:adapter =>"postgresql",
:host => "...",
:username => "...",
:database => "...")
Manufacturer.find_each do |m|
Company.new do |c|
c.name = m.name
c.location = m.geography
c.save
end
end
Manufacturer.connection.close
end
However when copying between two databases with identical model names this doesn’t work because defining the class for the external database overrides the class in the current application. Any ideas?
You can override the table name for any model:
If you still want you models to be named after their tables, you can scope them in some module.
Also don’t forget that multiple db-queries run faster within a transaction.
Also you can put your db-connection params in
database.ymlunder different section and connect to it by passing its name to theestablish_connectionmethod:If there are multiple models, you can make some base class and derive your models from it: