在rails上连接到多个数据库 [英] Connecting to multiple databases in ruby on rails
问题描述
我有一个ruby在rails应用程序工作正常,并连接到数据库。现在我想从同一个应用程序连接到不同的数据库。数据模型可以完全相同。事实上,如果我连接到不同的数据库应用程序工作正常。但是我想连接到两个不同的数据库。
对于多数据库连接,需要将以下代码添加到database.yml文件。这里,我给出了从rails应用程序连接两个数据库的示例
config / database.yml
开发:
adapter:mysql2
数据库:db1_dev
用户名:root
密码:xyz
host:localhost
development_sec:
adapter:mysql2
数据库:db2_dev
用户名:root
密码:xyz
host:localhost
:
adapter:mysql2
数据库:db1_prod
用户名:root
密码:xyz
host:your-production-ip
production_sec:
adapter:mysql2
数据库:db2_prod
用户名:root
密码:xyz
主机: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
#你的代码在这里。
end
end
希望它能为你工作:)。 p>
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" 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
Hope it will work for you :) .
这篇关于在rails上连接到多个数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!