如何在 Heroku 中为一个 Rails 3.1 应用程序使用多个数据库?

2021-12-16 00:00:00 heroku mysql ruby-on-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

相关文章