gpt4 book ai didi

ruby-on-rails - 如何在 Heroku 上的 Rails 控制台内切换数据库?

转载 作者:行者123 更新时间:2023-12-03 08:51:12 24 4
gpt4 key购买 nike

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

我的计划是连接到一个数据库,通过 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 作为环境变量在 Heroku 上启动 Rails 控制台来连接到这个旧数据库:

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

但我不知道如何切换回新数据库以便更新内容。

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

最佳答案

问题是使用 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"]

然后,您可以使用建立_连接

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

引用(Establish a connection to another database only in a block?)

并运行 SQL 命令:

OtherDB.connection.execute("select count(*) from users")

关于ruby-on-rails - 如何在 Heroku 上的 Rails 控制台内切换数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58821436/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com