1

We have a few Rails 3 web sites that need to access a common database for order tracking and fulfillment.

Basically we want each site to have its own database and be able to access the common database as well.

I am thinking that creating a gem to access this second database is the way to go, but I am fairly new to Ruby and Rails.

Anyone done something like this before?

Any suggestions on how to implement this?

TWA
  • 12,756
  • 13
  • 56
  • 92
  • http://stackoverflow.com/questions/1298909/multiple-database-connection-in-rails (I use the approach in the first answer in one of my apps) – klochner Aug 04 '11 at 21:54

2 Answers2

1

Try with something like:

# WARNING: untested code
module DatabaseA
  class Connection < ActiveRecord::Base
    self.abstract_class = true
    establish_connection :my_custom_connection
  end

  def const_missing(name)
    model = Class.new(Object.const_get(name))
    model.connection = Connection.connection
    const_set(name, model)
  end
end

Then you should use your models from this module:

DatabaseA::User.new
Pablo Castellazzi
  • 4,164
  • 23
  • 20
1

I have written a gem to help with this: https://github.com/karledurante/secondbase

We use it in production now with rails 2 and rails 3 apps.