How do I work with two different databases on rails with active records?

I need to use different database connections in different Rails models. Is there a wrong hacker way to do this?

Any links or search keywords would be great :)

+41
ruby ruby-on-rails activerecord
Aug 04 '09 at 7:52
source share
6 answers

mikej is right. However, I wrote a stone that makes the model code connect a little cleaner, check it out .

+9
Aug 05 '09 at 1:06
source share

Add new sections to database.yml for example

 other_development: adapter: mysql database: otherdb_development username: root password: host: localhost other_production: adapter: mysql database: otherdb_production username: root password: host: localhost 

Add a class to lib/other_database.rb

 class OtherDatabase < ActiveRecord::Base establish_connection "other_#{RAILS_ENV}" end 

and then for each model that is not in a subclass of the default database, from OtherDatabase for example:

 class MyModel < OtherDatabase # my model code... end 
+112
Aug 04 '09 at 8:18
source share

I used the following to connect to 2 db in one application. I put them in the lib folder, since everything is loaded there.

 require 'active_record' class OldDatabase < ActiveRecord::Base self.abstract_class = true establish_connection( :adapter => 'mysql', :database => 'weather', :host => 'localhost', :username => 'root', :password => 'password' ) end class NewDatabase < ActiveRecord::Base self.abstract_class = true establish_connection( :adapter => 'mysql', :database => 'redmine', :host => 'localhost', :username => 'root', :password => 'password' ) end class WeatherData < OldDatabase end class Board < NewDatabase end 

Hope that helps

+12
Aug 20 '09 at 23:41
source share

Update for Rails 3.x:

 class MyModel < ActiveRecord::Base establish_connection "other_#{Rails.env}" end 
+9
Mar 09 '13 at 0:55
source share

I think the best way to connect to another database with an active model is to create a base class for an external database and then inherit from that database in your model. This method works great with rails 4.2.6 and 5.0.4

For example:

 # in /models/external_db/base.rb require 'active_record' class ExternalDb::Base < ActiveRecord::Base self.abstract_class = true establish_connection "external_db_#{Rails.env}".to_sym end 

And in your model class:

 # in /models/external_db/some_model.rb class ExternalDB::SomeModel < ExternalDb::Base # your code end 

But you have to define an external database in /config/database.yml

 # in /config/database.yml external_db_development: adapter: sqlite3 pool: 5 timeout: 5000 database: db/external_db_development.db external_db_production: adapter: sqlite3 pool: 5 timeout: 5000 database: db/external_db_production.db 
+1
Jul 08 '17 at 11:10
source share

In rails 4.1+ establish_connection symbol is now taken:

 class OtherDbModel < ActiveRecord::Base establish_connection :"other_#{Rails.env}" end 
0
Oct 06 '16 at 14:20
source share



All Articles