ruby-on-rails - 如何在rails 4中的单个rails应用程序中访问多个数据库?

标签 ruby-on-rails ruby-on-rails-4

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

我会像这样尝试

配置/数据库.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

第二个数据库
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

然后我不知道如何继续..

最佳答案

对于多数据库连接,需要在database.yml文件中添加如下代码。在这里,我给出了从 Rails 应用程序连接两个数据库的示例

配置/数据库.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

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

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

让我们假设,我们有两个模型 User 和 Category。 users 表在 db1_dev 和 db1_prod 中,类别表在 db2_dev 和 db2_prod 中。

品类模型
class Category < ActiveRecord::Base
  establish_connection "#{Rails.env}_sec"
end

同样,当你为第二个数据库添加新的迁移时,需要添加以下代码。
class CreateRewards < ActiveRecord::Migration
  def connection
    ActiveRecord::Base.establish_connection("#{Rails.env}_sec").connection
  end

  def change
    # your code goes here.
  end
end

希望它对你有用:)。

关于ruby-on-rails - 如何在rails 4中的单个rails应用程序中访问多个数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47448715/

相关文章:

jquery - 最佳实践 : Temporary Record with has_many association

ruby-on-rails - 如何在时间范围内获取记录

ruby-on-rails - 乘客 NGINX 模块失败

mysql - Rails 4 脚本 + 错误 : Migrating Data From One Table to Another

activerecord - Rails : Undefined method create for nil class

ruby-on-rails - 在 Rails 3 中没有尾部斜杠的情况下重定向到规范路由

ruby-on-rails - 未定义的方法 `to_sym' 为 1 :Fixnum

ruby-on-rails - 如何在Rails 4.0中填充activerecord时加载动画?

ruby-on-rails-4 - Rails 4、Turbolinks 和 Google Analytics - 跟踪异步模式点击会使常规跟踪无效

android - 在发布时获得多个相同的请求 pubnubv4 rails