There are times when my project can connect to multiple databases, what should I do? I looked up the information, most of it is said in the model establish_connection
to join to point to different databases, and some say to do a basic class, each model inherits this class, these statements are not wrong, but not concise, I do a summary.
MySQL and rails4.2 are used here.
One, each model is connected to each other
Modify the Database.yml as follows:
Default: &default
Adapter:mysql2
Encoding:utf8
Pool:5
Host:localhost
Username:username
Password:password
Database:databasename
Development:
<<: *default
Test
<<: *default
Database:databasename_test
Production
<<: *default
Database:databasename_production
Others
Development:
Adapter:mysql2
Encoding:utf8
Reconnect:true
Pool:5
Host:localhost
Username:username
Password:password
Database:databasename2
Production
Adapter:mysql2
Encoding:utf8
Reconnect:true
Pool:5
Host:localhost
Username:username
Password:password
Database:databasename2_production
Create a module to do the database connection, as follows
Module DatabaseConnection
def self.included (Base)
Base.establish_connection databasecnf[:others][rails.env] #DatabaseCnf是一个类, which is used to read the DATABASE.YML configuration.
End
End
Then include this module in each model that requires this connection, such as:
Class Company < ActiveRecord::Base
Include DatabaseConnection
End
This company class can be connected to the companies table of the database under others, and the operation is the same as the default.
Second, create a connection class, you need to inherit this class
The DATABASE.YML configuration file does not change.
Create a database connection class:
Class DatabaseConnection < ActiveRecord::Base
Self.abstract_class = True #共用连接池 to reduce the consumption of database connections
Establish_connection databasecnf[:others][rails.env] #DatabaseCnf是一个类, which is used to read the DATABASE.YML configuration.
End
The model of the connection is then required to inherit the class.
Class Company < DatabaseConnection
End
This company is the companies table of the database used in the others.
Summing up, I think the second way is better, it can share the link pool, reduce the database connection, reduce the consumption of system resources.
Two ways Rails connects to multiple databases