CHAPTER 8 ?– ACTIVE RECORD AND THE REAL WORLD 201
When working with multiple databases (and really when working with a single database
as well), it can be handy to store your connection parameters in a YAML configuration file. For
this example, the file will be called database.yml, but you can name it whatever you want. The
file should look something like this:
database1:
adapter: mysql
host: localhost
username: myuser
password: mypass
database: db1
database2:
adapter: mysql
host: remote.host
username: youruser
password: yourpass
database: db2
With the preceding configuration file in hand, we can now use it to individually configure
our Active Record models to talk to the separate databases. We will first create a separate
Active Record class that our real Active Record classes will extend, which will make our code
cleaner and easier to maintain:
require "rubygems"
require "activerecord"
@config = YAML.load_file(File.join(File.dirname(__FILE__), 'database.yml'))
class LocalDatabase < ActiveRecord::Base
establish_connection @config['database1']
end
class RemoteDatabase < ActiveRecord::Base
establish_connection @config['database2']
end
The Active Record classes LocalDatabase and RemoteDatabase can now be used to indicate
which database each particular Active Record class uses.
Pages:
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465