如何在Heroku的Rails控制台内切换数据库?

我正在尝试将用户从一个系统迁移到另一个系统。每个系统都有自己的数据库和不同的类。

我的计划是连接到一个数据库,并通过SQL命令从一个数据库中读取一些信息:

activeRecord::Base.connection.execute(sql_command)

处理数据,然后使用常规模型在新数据库上写入一些结果。

我计划在Sidekiq工作中进行此操作,但是我试图使用Heroku上的Rails控制台进行一些测试。

这应该很简单,但是事实证明这很困难。

当我在Heroku上启动Rails控制台时。我正在连接到DATABASE_URL,可以,但是当我尝试连接到旧数据库并执行命令时,如下所示:

activeRecord::Base.establish_connection(adapter: "postgresql",encoding: "unicode",pool: 10,url: "postgres://...info...")
activeRecord::Base.connection.execute("select count(*) from users")

我最终得到:

PG::ConnectionBad (could not connect to server: No such file or directory)
    Is the server running locally and accepting
    connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

但是,我可以通过使用DATABASE_URL作为env变量在heroku上启动我的rails控制台来连接到该旧数据库:

$ heroku run 'DATABASE_URL=postgres://...info... rails console' -a  console' -a app

但是我不知道如何切换回新数据库,所以我可以进行更新。

在heroku上使用Rails控制台时,如何在运行时切换数据库?

baobeisl521 回答:如何在Heroku的Rails控制台内切换数据库?

为什么要尝试在运行时切换数据库?为什么不将两者同时连接并在模型级别指定它们从哪个数据库读取/写入数据? Rails支持连接多个数据库并在各个模型中指定要使用的数据库连接:https://guides.rubyonrails.org/active_record_multiple_databases.html

,

问题是使用url:无效,需要指定所有参数。

config = {"adapter"=>"postgresql","encoding"=>"unicode","pool"=>10,"username"=>"u...","password"=>"p...","port"=>5432,"database"=>"d...","host"=>"ec2..."}

如果您要使用3tier数据库yml,则可以使用以下方法:

config = ActiveRecord::Base.configurations["production"]["seconddb"]

然后,您可以使用establish_connection

ActiveRecord::Base.establish_connection(config)
ActiveRecord::Base.connection.execute("select count(*) from users")

一旦我开始指定用户名,密码,端口,数据库和主机,所有这些都像魅力一样。

要同时使用两个数据库,一个好的方法是创建一个类

class OtherDB < ActiveRecord::Base
  establish_connection(ActiveRecord::Base.configurations["production"]["seconddb"])
end

那你可以这样称呼

OtherDB.table_name = "table_name"
OtherDB.first

ref(Establish a connection to another database only in a block?

并运行SQL命令:

OtherDB.connection.execute("select count(*) from users")
本文链接:https://www.f2er.com/3116389.html

大家都在问