如何在rails 4中的单个rails应用程序中访问多个数据库? [英] how to access multiple databases in single rails application in rails 4?

查看:33
本文介绍了如何在rails 4中的单个rails应用程序中访问多个数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to rails, don't know how to access multiple databases in rails single application.

我会试试这个

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

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

then i don't know how to proceed..

推荐答案

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

For multiple database connection, you need to add the following codes to the database.yml file. Here, I am giving the example of connecting two databases from a rails application

config/database.yml

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

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

Here I have used two databases for the development and production environment.

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

Now we need to connect the model to databases. When you are running your application in development and production mode, all the models will be mapped through the development and production db parameters those been mentioned in your database.yml. So for some model we need to connect to other database.

让我们假设,我们有两个模型用户和类别.users 表在 db1_dev 和 db1_prod 中,categories 表在 db2_dev 和 db2_prod 中.

Lets assume that, we have two models User and Category. The users table is in db1_dev and db1_prod, the categories table in db2_dev and db2_prod.

类别模型

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

同理,在为第二个数据库添加新的迁移时,也需要添加如下代码.

Similarly, when you adding the new migration for the second database, need to add following code to it.

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

  def change
    # your code goes here.
  end
end

希望它对你有用:).

这篇关于如何在rails 4中的单个rails应用程序中访问多个数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆