如何在Rails 4中的单个Rails应用程序中访问多个数据库?

San*_*har 4 ruby-on-rails ruby-on-rails-4

我是Rails的新手,不知道如何在Rails单个应用程序中访问多个数据库。

我会这样尝试

config / database.yml

default: &default
  adapter: mysql2
  encoding: utf8
  pool: 5
  username: root
  password: root
  socket: /var/run/mysqld/mysqld.sock
  reconnect: true

development:
  <<: *default
  database: connection_development
<<: *default
  database: connection_test
Run Code Online (Sandbox Code Playgroud)

第二个数据库

log_database_production:
  adapter: mysql2
  encoding: utf8
  pool: 5
  host: 192.168.100.97
  port: 3306        #ip address of server with other postgres database
  username: root
  password: root
  database: hrms_development
  reconnect: true
Run Code Online (Sandbox Code Playgroud)

那我不知道该怎么办..

pun*_*t18 7

对于多个数据库连接,您需要将以下代码添加到database.yml文件中。在这里,我以从Rails应用程序连接两个数据库为例

config / database.yml

development:
  adapter: mysql2
  database: db1_dev
  username: root
  password: xyz
  host: localhost

development_sec:
  adapter: mysql2
  database: db2_dev
  username: root
  password: xyz
  host: localhost

production:
  adapter: mysql2
  database: db1_prod
  username: root
  password: xyz
  host: your-production-ip

production_sec:
  adapter: mysql2
  database: db2_prod
  username: root
  password: xyz
  host: your-production-ip
Run Code Online (Sandbox Code Playgroud)

在这里,我使用了两个用于开发和生产环境的数据库。

现在我们需要将模型连接到数据库。在开发和生产模式下运行应用程序时,所有模型都将通过database.yml中提到的开发和生产db参数进行映射。因此,对于某些模型,我们需要连接到其他数据库。

假设有两个模型User和Category。users表位于db1_dev和db1_prod中,类别表位于db2_dev和db2_prod中。

类别模型

class Category < ActiveRecord::Base
  establish_connection "#{Rails.env}_sec"
end
Run Code Online (Sandbox Code Playgroud)

同样,在为第二个数据库添加新迁移时,需要向其添加以下代码。

class CreateRewards < ActiveRecord::Migration
  def connection
    ActiveRecord::Base.establish_connection("#{Rails.env}_sec").connection
  end

  def change
    # your code goes here.
  end
end
Run Code Online (Sandbox Code Playgroud)

希望它对您有用:)。