直接进入正题
1.首先正常database.yml
文件如下所示
default: &default
adapter: mysql2
encoding: utf8mb4
pool: 5
username: root
password:
host: localhost
port: 3306
socket: /tmp/mysql.sock
development:
<<: *default
database: hy
test:
<<: *default
database: hy_test
staging:
<<: *default
database: hy_pro
pool: 25
username: root
password: 123456
host: 192.168.1.1
port: 3306
production:
<<: *default
database: hy_production
pool: 25
username: root
password: 123456
host: 192.168.1.1
port: 3306
2.接下来是连接多个数据库的database.yml文件如下
default: &default
adapter: mysql2
encoding: utf8mb4
pool: 5
username: root
password:
host: localhost
port: 3306
socket: /tmp/mysql.sock
development:
<<: *default
database: hy
test:
<<: *default
database: hy_test
staging:
<<: *default
database: hy_pro
pool: 25
username: root
password: 123456
host: 192.168.1.1
port: 3306
production:
<<: *default
database: hy_production
pool: 25
username: root
password: 123456
host: 192.168.1.1
port: 3306
hy_last:
default: &default
adapter: mysql2
encoding: utf8mb4
pool: 5
username: root
password:
host: localhost
port: 3306
socket: /tmp/mysql.sock
development:
<<: *default
database: hy_last
test:
<<: *default
database: hy_last_test
staging:
<<: *default
database: hy_last_staging
pool: 25
username: root
password: 123456
host: 192.168.1.1
port: 3306
production:
<<: *default
database: hy_last_production
pool: 25
username: hy_last
password: 123456
host: 192.168.1.1
port: 3306
3.接下来就是配置数据库的model层了
(1)首先默认情况下就是按默认的database.yml
文件配置的
(2)连接第二个数据的配置是先建立一个父model
文件,之后让别的model
继承他即可
文件/app/models/hy_last_model.rb
class HyLastModel < ActiveRecord::Base
begin
config = ActiveRecord::Base.configurations["hy_last"][Rails.env] || Rails.application.config.database_configuration["hy_last"][Rails.env]
ActiveRecord::Base.establish_connection(config)
rescue Exception => e
Rails.logger.error("Failed to connect to #{config["adapter"]} databaseName: #{config["database"]}")
Rails.logger.error(e.message)
Rails.logger.error(e.backtrace.join("\n"))
end
end
4.让子类实现它/app/models/hy_test.rb
class HyTest < HyLastModel
self.table_name = "tests"//指代数据库表名
end