How to use multiple databases for one rails 3.1 app in Heroku?(如何在 Heroku 中为一个 Rails 3.1 应用程序使用多个数据库?)
问题描述
My Rails 3.1 应用连接了 2 个数据库,一个是默认的,另一个是 Amazon RDS MYSQL 实例.
My Rails 3.1 application connects to 2 databases, one is the default, the other is an Amazon RDS MYSQL instance.
当前的database.yml 包含两个生产数据库连接.需要从第二个数据库中拉取的模型只需使用
The current database.yml contains two production database connections. The models that need to pull from the second database simply use
establish_connection "production_on_amazon"
不幸的是,Heroku 会覆盖您的 database.yml,并且似乎只包含一个数据库连接.有谁知道我如何添加或配置我的第二个?
Unfortunately Heroku overwrites your database.yml, and only seems to inlcude one database connection. Does anyone know how I can add or configure my second?
运行heroku config"我可以看到列出了 2 个数据库,但似乎无法配置为连接到这两个数据库.也许以某种方式将我的默认设置设置为 Heroku 上的 SHARED_DATABASE_URL 数据库并将备用设置设置为指向亚马逊的 DATABASE_URL...
Running "heroku config" I can see there are 2 DB's listed but cant seem to configure to connect to both. Perhaps somehow set my default to the SHARED_DATABASE_URL db on Heroku and set the alternate to the DATABASE_URL which points to Amazon...
推荐答案
关于 Neil 的回答,这里有一个方法.不是开箱即用的解决方案,但可能会给您一个想法....../lib/active_record_extensions.rb
Regarding Neil's answer, here is a way to do it. Not an out-of-box solution, but might give you an idea... /lib/active_record_extensions.rb
module ActiveRecordExtensions
class Shard < ActiveRecord::Base
#need to switch to the shard database connection from heroku config
primary_database_url = ENV['PRIMARY_DATABASE_URL']
if(!primary_database_url.nil?)
parsed_connection_string = primary_database_url.split("://")
adapter = parsed_connection_string[0]
parsed_connection_string = parsed_connection_string[1].split(":")
username = parsed_connection_string[0]
parsed_connection_string = parsed_connection_string[1].split("@")
password = parsed_connection_string[0]
parsed_connection_string = parsed_connection_string[1].split("/")
host = parsed_connection_string[0]
database = parsed_connection_string[1]
establish_connection(
:adapter => adapter,
:host => host,
:username => username,
:password => password,
:database => database,
:port => 3306,
:pool => 5,
:timeout => 5000
)
else
self.establish_connection "shard_#{Rails.env}"
end
end
class ShardMigration < ActiveRecord::Migration
def connection
ActiveRecord::Shard.connection
end
end
end
所以你的模型应该只扩展 ActiveRecord::Shard 而不是 Base
So your model should just extend ActiveRecord::Shard instead of Base
这篇关于如何在 Heroku 中为一个 Rails 3.1 应用程序使用多个数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Heroku 中为一个 Rails 3.1 应用程序使用多个数据库?


- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- SQL 临时表问题 2022-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 更改自动增量起始编号? 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01