在 ruby on rails 中连接到多个数据库 [英] Connecting to multiple databases in ruby on rails
问题描述
我有一个运行良好的 ruby on rails 应用程序并连接到数据库.现在我想从同一个应用程序连接到不同的数据库.数据模型可以完全相同.事实上,如果我连接到不同的数据库,应用程序工作正常.但是我想连接到两个不同的数据库.ruby on rails 有可能吗?
多数据库连接需要在database.yml文件中添加如下代码.在这里,我给出了从 Rails 应用程序连接两个数据库的示例
config/database.yml
开发:适配器:mysql2数据库:db1_dev用户名:root密码:xyz主机:本地主机development_sec:适配器:mysql2数据库:db2_dev用户名:root密码:xyz主机:本地主机生产:适配器:mysql2数据库:db1_prod用户名:root密码:xyz主机:你的生产IP生产秒:适配器:mysql2数据库:db2_prod用户名:root密码:xyz主机:你的生产IP
这里我使用了开发和生产环境的两个数据库.
现在我们需要将模型连接到数据库.当您在开发和生产模式下运行应用程序时,所有模型都将通过您的 database.yml 中提到的开发和生产数据库参数进行映射.所以对于某些模型,我们需要连接到其他数据库.
让我们假设,我们有两个模型用户和类别.users 表在 db1_dev 和 db1_prod 中,categories 表在 db2_dev 和 db2_prod 中.
类别模型
class 类别 活动记录::基础建立连接#{Rails.env}_sec".to_sym结尾
同样,当您为第二个数据库添加新的迁移时,需要添加以下代码.
类 CreateRewards <ActiveRecord::迁移默认连接ActiveRecord::Base.establish_connection("#{Rails.env}_sec".to_sym).connection结尾定义变化# 你的代码放在这里.结尾结尾
希望它对你有用:).
I have a ruby on rails application working fine and connected to a database. Now i want to connect to a different database from the same application. The data model can be exactly the same. In fact if i connect to the different database the application works fine. However I want to connect to two different databases. Is it possible in ruby on 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
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.
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.
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.
Category model
class Category < ActiveRecord::Base
establish_connection "#{Rails.env}_sec".to_sym
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".to_sym).connection
end
def change
# your code goes here.
end
end
Hope it will work for you :) .
这篇关于在 ruby on rails 中连接到多个数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!