运行时在 ruby​​ 中连接到两个不同的数据库 [英] Connecting to two different database in ruby at runtime

查看:40
本文介绍了运行时在 ruby​​ 中连接到两个不同的数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在开发环境和生产环境中托管了一个数据库.我正在编写一个 API,它基于请求中的参数将写入开发或生产数据库中的表.我已将两个条目放在 database.yml 文件中:

I have a database being hosted in development environment and production environment. I am writing an API which based on a parameter in request will write to table in either development or production DB. I have put both entries in by database.yml file :

development:   
  adapter: mysql2   
  database: db1  
  username: root  
  password:  
  timeout: 5000   
  host: a.b.c.d   
  pool: 5  
  port: 1234

production: 
  adapter: mysql2 
  database: db1 
  username: root  
  password:  
  timeout: 5000  
  host: a.b.c.e  
  pool: 5  
  port: 1234

这是我的活动记录:

class table1 < ActiveRecord::Base  
  self.table_name = 'table1' 
end

如何根据请求参数写入不同的环境?

How do i write to different environments based on a request parameter ?

推荐答案

您可以为同一张表使用两个模型,一个连接到生产数据库,另一个连接到开发数据库.

You could use two models for the same table, one connected to the production database and the other connected to the development database.

假设您的连接参数在变量 $production$development 中.

Lets say your connection parameters are in the variables $production and $development.

您还必须调整代码以了解要使用的模型.

You would also have to adapt your code to know which model to use.

class Table1 < ActiveRecord::Base  
 establish_connection($production)
 self.table_name = 'table1' 
end

class Table1test < ActiveRecord::Base  
 establish_connection($development)
 self.table_name = 'table1' 
end

这篇关于运行时在 ruby​​ 中连接到两个不同的数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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