Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1
Connecting to Multiple Databases | 117

legacy:
adapter: mysql
database: my_db
username: user
password: pass
host: legacy_host

new:
adapter: mysql
database: my_db
username: user
password: pass
host: new_host

Then, you can simply refer to these configuration blocks from the ActiveRecord class
definition using theActiveRecord::Base.establish_connection method:


class LegacyClient < ActiveRecord::Base
establish_connection "legacy"
end

class Client < ActiveRecord::Base
establish_connection "new"
end

This approach also works with multiple Rails environments. Just specify each envi-
ronment in thedatabase.yml file as usual:


legacy_development:
#...

legacy_test:
#...

legacy_production:
#...

new_development:
#...

new_test:
#...

new_production:
#...

Then, use theRAILS_ENV constant in the database configuration block name:


class LegacyClient < ActiveRecord::Base
establish_connection "legacy_#{RAILS_ENV}"
end

class Client < ActiveRecord::Base
establish_connection "new_#{RAILS_ENV}"
end
Free download pdf