Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make rails external database calls?

So i'd like to be able to add an external database to my config/database.yml Then model one table from it.

Is this possible? I haven't been able to figure out how.

"Connection to multiple databases in different models

Connections are usually created through ActiveRecord::Base.establish_connection and retrieved by ActiveRecord::Base.connection. All classes inheriting from ActiveRecord::Base will use this connection. But you can also set a class-specific connection. For example, if Course is an ActiveRecord::Base, but resides in a different database, you can just say Course.establish_connection and Course and all of its subclasses will use this connection instead.

This feature is implemented by keeping a connection pool in ActiveRecord::Base that is a Hash indexed by the class. If a connection is requested, the retrieve_connection method will go up the class-hierarchy until a connection is found in the connection pool. "

like image 731
Kirby Avatar asked Jan 18 '11 18:01

Kirby


People also ask

What three databases are referred to by a Rails application?

Ruby on Rails recommends to create three databases - a database each for development, testing, and production environment.


1 Answers

First, define the connection information in database.yml:

my_external_db:
  adapter: mysql
  username: ...
  ....

Then, create the model and connect it to the external db

class MyExternalModel < ActiveRecord::Base
  establish_connection(:my_external_db)
  set_table_name 'my_external_table'
end
like image 161
John Douthat Avatar answered Oct 07 '22 01:10

John Douthat