Fetching Data From Mulitple Databases

Hello,

I have read several articles on methods to fetch data from several
databases using Rails. The general consensus seems to be that working
with one database is better when possible, but when it’s not possible,
you ought to establish your database connection in the model rather
than the controller for a variety of reasons. However, just about all
the examples I’ve found still establish the database connection in the
controller. Can someone provide me some assistance in establishing a
database connection in a model?

More specifically, my problem is that I am trying to store user info
in one database and the products they own in another. I don’t get to
choose the database design, I just get to work with what I’ve been
given. The products database is the default database. When user
information is requested, I need to connect to the users database and
fetch it from there. Presently, it is done through a SOAP API to a
third database which is really slow and problematic (the SOAP calls
AND the database, that is - probably the initial developer’s fault).

Any suggestions would be helpful. Thanks!

Hi Matt, just define your connection in database.yml like the rest of
your connections, but instead of “production”, “test”, etc name is
something else like “usersdb”. Then in your users model, use:

establish_connection :usersdb

Matt W. wrote:


Sincerely,

William P.