时间:2021-07-01 10:21:17 帮助过:2人阅读
这里使用的是mysql和rails4.2
修改database.yml如下:
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
创建一个module做数据库连接,如下
module DatabaseConnection
    def self.included(base)
        base.establish_connection DatabaseCnf[:others][Rails.env]   #DatabaseCnf是一个类,它用来读取database.yml配置。
      end
  end
然后在每个需要这个连接的model里include这个module,就可以了,如:
  class Company < ActiveRecord::Base
    include DatabaseConnection
  end
这个Company类就可以连接到others下的数据库的companies表了,操作和默认相同。
database.yml配置文件不变。
创建一个数据库连接类:
class DatabaseConnection < ActiveRecord::Base
  self.abstract_class = true    #共用连接池,减少数据库连接的消耗
  establish_connection DatabaseCnf[:others][Rails.env]  #DatabaseCnf是一个类,它用来读取database.yml配置。
end
然后需要这个连接的model继承这个类即可。
class Company < DatabaseConnection
end
这样的Company就是使用的others下的数据库的companies表了。
总结,我觉得使用第二种方式更好一些,它可以共享链接池,减少数据库连接,降低系统资源的消耗。
Rails 连接多个数据库的两种方式
标签: