TWA
TWA

Reputation: 12816

Creating a Ruby gem to Access a Second Database from Multiple Rails Applications

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?

Upvotes: 1

Views: 1144

Answers (2)

karle durante
karle durante

Reputation: 11

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.

Upvotes: 1

Pablo Castellazzi
Pablo Castellazzi

Reputation: 4184

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

Upvotes: 1

Related Questions