Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i work with two different databases in rails with active records?

I need to use different database connections in different Rails models. Is there a not-so-hacky way to do that?

Any links or search keywords would be great :)

like image 850
gustavgans Avatar asked Aug 04 '09 07:08

gustavgans


People also ask

Is it possible to connect to multiple databases simultaneously?

This can be done several times to connect to different databases, with the restriction that it will only allow one connection to the same database. If you try to use a database from multiple instances of the same application either on the same computer or on different computers you will receive an error message.

How can we use two databases to a single application?

so, based on user login, the application should connect different database server. For Ex: if user "xxx" login with credential and belogs to "ABC" company and the database is "ABC", then ABC data need to display on the web page.

How do I connect to a different database?

1. Create a linked server in DB invironment, then create a SP to take care of it. 2. Get two DataSets for them, then merge two datatables into one based on usersID.


1 Answers

Add new sections to your database.yml e.g.

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 in lib/other_database.rb

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

and then for each model which isn't in the default database subclass from OtherDatabase e.g.:

class MyModel < OtherDatabase    # my model code... end 
like image 97
mikej Avatar answered Oct 13 '22 09:10

mikej