Acts As Partitioned

Allows ActiveRecord models to connect to different databases on-the-fly.

Horizontal Partitioning is when you remove rows from one table and put
them in a separate table (usually on a separate database, usually on a 
separate machine.)

For example, say you have a users table with one million rows and it
is getting too large.  You can cap it at one million and say all new
users will go into the users table on the second database.  Then when
that one reaches one million rows all new users will go into a third
database, etc.

You can call

	establish_connection name_of_db_in_database_dot_yaml

yourself to change the connection, but if you have a lot of models
with has_many, has_one, or belongs_to associations and some complex 
logic to determine which partition is correct, we recommend this plugin.

All you have to do is add "acts_as_partitioned" to your model classes:

class User < ActiveRecord::Base

Then, add something to your Application class to call:

on every call.  For example:

class ApplicationController < ActionController::Base
  before_filter :set_stuff
  def set_stuff
    # you have to decide what id you'll use   

Then modify the acts_as_partitioned.rb file in this plugin and change
the "set_partition" method to include your logic for how to pick
a partition based on an id.

	def set_partition(id)
	  if RAILS_ENV == 'test'
	  # add all your partitions here, we make partition1 the normal
	  # production database with RAILS_ENV
	  if not @@partition_connections
	    @@partition_connections = []
	    @@partition_connections[0] = nil	
	    @@partition_connections[1] = get_connection_klass(RAILS_ENV)  
	    @@partition_connections[2] = get_connection_klass('partition2')
	    @@partition_connections[3] = get_connection_klass('partition3')		    
	  # add your logic for how to pick the partition based on the id here
	  partition_id = 1
	  if id >= 2000000 and id < 3000000
	    partition_id = 2
	  elsif id >= 3000000
	    partition_id = 3
	  @@my_connection = @@partition_connections[partition_id]     
One more method to change:

        def set_to_current
          if not RAILS_ENV == 'test'
            @@my_connection = @@partition_connections[3]
This method is putting all new users into the 3rd database.  But this
doesn't have to be hard coded like this.  You can have a lookup
to determine which is the "current" partition for all new users.

And you'll need to call

before adding a new user.

And that's it.  Brought to you by the team.

Feb 14, 2007