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 environment
in the database.yml file as usual:
legacy_development:
# ...
legacy_test:
# ...
legacy_production:
# ...
new_development:
# ...
new_test:
# ...
new_production:
# ...
Then, use the RAILS_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
118 | Chapter 4: Database
You can go one step further and DRY this code up by using class inheritance to
define which database an ActiveRecord class belongs to:
class LegacyDb < ActiveRecord::Base
self.abstract_class = true
establish_connection "legacy_#{RAILS_ENV}"
end
class NewDb < ActiveRecord::Base
self.abstract_class = true
establish_connection "new_#{RAILS_ENV}"
end
class LegacyClient < LegacyDb
end
class Client < NewDb
end
The self.abstract_class = true statements tell ActiveRecord that the LegacyDb and
NewDb classes cannot be instantiated themselves; since they represent database connections,
they are not backed by concrete tables in the database.
Magic Multi-Connections
Dr Nic Williams??™s Magic Multi-Connections gem (http://magicmodels.
Pages:
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186