天天看點

[ruby on rails]同時連結多資料庫

  • database.yml
default: &default
  encoding: utf8
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  wait_timeout: 60
  
oracle_development: #名字可自定義,但是不能重複。
  <<: *default
  adapter: oracle_enhanced
  host: xxx.xxx.xxx.xx
  username: root
  password: 123456
  database: oracle_dev
  port: 1521 # Oracle 的端口号,Mysql為3306,mysql一般不寫 

mysql_development:
  <<: *default
  adapter: mysql2
  host: xxx.xxx.xxx.xx
  username: root
  password: 123456
  database: mysql_dev
           

第一種使用方法

  • 建立app/other_database_models/other_application.rb
class OtherApplication < ActiveRecord::Base #OtherApplication隻是個名字,可随便定義
  self.abstract_class = true
  establish_connection :oracle_development # database.yml中配置的資料庫
end
           
  • 建立app/other_database_models/user.rb
  • 使用oracle_development中的users表
class User < Oth