gpt4 book ai didi

ruby-on-rails - rails : Loading schema into secondary database

转载 作者:行者123 更新时间:2023-12-04 06:33:01 28 4
gpt4 key购买 nike

如何将模式加载到辅助数据库中?似乎 Rails 不支持同时维护主要ActiveRecord::Base.connection 设置辅助数据库连接的能力。

域定义

我们有使用辅助数据库的模型。我们的主数据库是 MySQL,辅助数据库是 PostgreSQL。要使用 ActiveRecord 文档的示例:

|
+-- Book
| |
| +-- ScaryBook
| +-- GoodBook
+-- Author
+-- BankAccount

其中 Book 是抽象的,使用 establish_connection 连接到 Postgres。

在处理数据库时,我们既可以使用ActiveRecord::Base.connection,也可以使用Book.connection

模式转储

即:Rails database tasks in the schema namespace允许我们这样转储架构:

ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, 文件)

这将允许我执行以下操作:

ActiveRecord::SchemaDumper.dump(Book.connection, file)

问题:模式加载

但是,load 任务没有这种能力。它只是将架构文件作为一个整体来评估:

desc 'Load a schema.rb file into the database'
task :load => :environment do
file = ENV['SCHEMA'] || "#{Rails.root}/db/schema.rb"
if File.exists?(file)
load(file)
else
abort %{#{file} doesn't exist yet. Run "rake db:migrate" to create it then try again. If you do not intend to use a database, you should instead alter #{Rails.root}/config/application.rb to limit the frameworks that will be loaded}
end
end

模式文件在没有连接定义的情况下运行 ActiveRecord::Schema.define。 (注意 the define method 在“当前连接适配器”的上下文中运行)。

如何在不执行临时 ActiveRecord::Base.establish_connection 的情况下更改“当前连接适配器”,这不是我想做的?我基本上想在 Book.connection 的上下文中运行 ActiveRecord::Schema.define

编辑:我会注意到我需要一个外部运行rake任务的编程解决方案,这就是为什么我在内部寻找rake任务以查看它们的原因'实际上在做。

最佳答案

如何转储架构:

ActiveRecord::Base.establish_connection "custom_db_#{Rails.env}".to_sym 
File.open Rails.root.join('db/schema_custom_db.rb'), 'w:utf-8' do |file|
ActiveRecord::SchemaDumper.dump ActiveRecord::Base.connection, file
end

如何加载模式:

ActiveRecord::Tasks::DatabaseTasks.load_schema_current :ruby, Rails.root.join('db/schema_custom_db.rb'), "custom_db_#{Rails.env}"

关于ruby-on-rails - rails : Loading schema into secondary database,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21055666/

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