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

(Tuis.) #1

118 | Chapter 4: Database


You can go one step further and DRY this code up by using class inheritance to
define which database anActiveRecord 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

Theself.abstract_class = truestatements tell ActiveRecord that theLegacyDband
NewDbclasses cannot be instantiated themselves; since they represent database con-
nections, they are not backed by concrete tables in the database.


Magic Multi-Connections


Dr Nic Williams’s Magic Multi-Connections gem (http://magicmodels.rubyforge.org/
magic_multi_connections/) allows you to connect to different databases concurrently
from the same application. This is very useful when using one master and several
read-only slaves serving the same models. The syntax is transparent; it uses module
namespaces and imports the models (ActiveRecord::Base subclasses) into the
namespaces.


For a single-master situation, you could define another database connection in
database.yml for the read slave:


read_slave:
adapter: postgresql
database: read_only_production
username: user
password: pass
host: read_slave_host

This database is backed by a module, which mirrors the ActiveRecord classes using
this database connection:


require 'magic_multi_connections'
module ReadSlave
establish_connection :read_slave
end

Now, all pre-existing models can be accessed through theread_slaveconnection by
prefixing the model class withReadSlave::.

Free download pdf