How can I dynamically change the Active Record database for all models in Ruby on Rails?

You can also do this easily without hardcoding anything and run migrations automatically:

customer = CustomerModel.find(id)
spec = CustomerModel.configurations[RAILS_ENV]
new_spec = spec.clone
new_spec["database"] = customer.database_name
ActiveRecord::Base.establish_connection(new_spec)
ActiveRecord::Migrator.migrate("db/migrate_data/", nil)

I find it useful to re-establish the old connection on a particular model afterwards:

CustomerModel.establish_connection(spec)

you can change the connection to ActiveRecord at any time by calling ActiveRecord::Base.establish_connection(...)

IE:

 ActiveRecord::Base.establish_connection({:adapter => "mysql", :database => new_name, :host => "olddev",
    :username => "root", :password => "password" })

It's been a while since this question has been created, but I have to say that there is another way too:

conn_config = ActiveRecord::Base.connection_config
conn_config[:database] = new_database
ActiveRecord::Base.establish_connection conn_config