0

I'm trying to connect to 2 databases in my Rails application.

I created 2 models in my RoR app which is for 2 tables on 2 different databases.

I know how to connect to the other database before accessing the table using:

ActiveRecord::Base.establish_connection() 

But what I'm trying to accomplish is to automatically set the connection to the correct database every time I call on that model/table because I'm required to have different databases.

Just like the before_filter on the Rails controllers, how can I get my rails app to run a method that establishes a connection like this:

 def set_database 
      ActiveRecord::Base.establish_connection({ :adapter => 'nuodb',:database => 'test_db',:host => 'localhost',:username => 'test_username',:password => 'test_password', :schema  => 'TEST_SCHEMA'})
    end

I would like to run this method everytime I call a model.

I've been looking at ActiveModel::Callbacks but I can't seem to find a callback for this.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Patrick Angodung
  • 4,625
  • 3
  • 14
  • 18

1 Answers1

1

All your models inherit from ActiveRecord::Base. So establish_connection is available in the model directly.

# config/database.yml

development:
 # first database configuration

development_sec:
 # second database configuration

Then in your model use this:

class MyModel < ActiveRecord::Base
 establish_connection "#{Rails.env}_sec"
end

Or consider using a gem like connection_ninja

manu29.d
  • 1,538
  • 1
  • 11
  • 15