Connecting and Associating multiple databases and their tables in rails(Part 1)
There are several steps that needs to follow to connect with multiple database and create association between two different tables of two different databases
First you need to modify your database.yml
1.)database.yml:
main_development:
# development configuration goes here
secondary_development:
# development configuration to external database goes here
# same for test and production...
2.)Models:
If you have two different databases the you would have multiple tables in each database and off-Course multiple models in each db now the question is how to establish the connection between two models of two different database.
But Rails provide it in easy way
#Model in main_database
To manually
connect
each model of main_database with secondary database you need to establish a connection to that database like:
class
Astronaut < ActiveRecord::Base
establish_connection
"nasa_#{Rails.env}"
end
or
create a model which establishes the connection to secondary database and now each model can inherit or not to that model
class
NasaTable < ActiveRecord::Base
self.abstract_class = true
establish_connection
"nasa_#{Rails.env}"
end
Question: Why the hell are you creating a abstract class and what is the problem if I would write establish connection to each model in which I needs to connect to the secondary database or main_database.
Answer: if you do this you will end up with multiple connection pools within two databases so create only one connection.
The self.abstract_class = true
tells Active Record to not
look up for a table, since this class is only used to add custom
settings we don’t need any database table for it.class
Astronaut < NasaTable
self.table_name='astronauts'
has_many
:missions
has_many
:shuttles
, through:
:missions
end
class
Shuttle < NasaTable
self.table_name='shuttles'
has_many
:missions
has_many
:astronauts
, through:
:missions
end
class
Mission < NasaTable
self.table_name='missions'
belongs_to
:astronaut
belongs_to
:shuttle
end
# test
shuttle = Shuttle.create name:
"Endeavor"
shuttle.astronauts << Astronaut.create(name:
"Mark Kelly"
)
assert_equal
1
, shuttle.reload.astronauts.count
self.table_name tells the name of the database for that particular model it is not really not necessary.
Comments
Post a Comment