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

编程入门 行业动态 更新时间:2024-10-23 19:33:46
本文介绍了如何在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应用程序中访问多个数据库?

本文发布于:2023-10-25 22:13:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1528257.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   应用程序   数据库   如何在   rails

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!