是否可以在辅助数据库上使用 Rails rake 任务?

Is it possible to use Rails rake tasks on secondary databases?

如果您在给定环境中使用多个数据库(例如,跨数据库对表进行分片),是否可以使用内置的 Rails rake tasks 来操作上述环境的主要数据库之外的数据库?

例如如果我对一组模型使用特定的 connection details,我可以使用 rake db:create 来创建所述数据库吗?

如果是,怎么做?

我实际上已经覆盖了内置的 Rails rake 任务以操作第二个数据库。巧妙的是,它也完全适用于原始的 rake 任务。

这就是我所做的...归功于 Nikolay Sturm,因为我的佣金任务基于他的博客。

我在 database.yml 中添加了新的数据库设置,详见我链接的博客。

您还创建了一个具有这些数据库设置的基础模型:

class BaseModel < ActiveRecord::Base
  establish_connection "database_connection_name"
  self.abstract_class = true #you want to make this an abstract class because you don't have a table for this
end

然后,您可以让连接到此辅助数据库的任何模型继承自您的 BaseModel。

在您的 rake 任务中,您将其设置如下(请记住,这是针对 Postgres 连接的。)

namespace :db do
  desc 'create database'
  task create: :environment do
    connection_config = BaseModel.connection_config #rename BaseModel to name of your model
    ActiveRecord::Base.establish_connection connection_config.merge('database => 'postgres') #you don't need this bit if you're not using Postgres
    ActiveRecord::Base.connection.create_database connection_config[:database], connection_config
    ActiveRecord::Base.establish_connection connection_config
  end

  desc 'migrate database'
  task migrate: :environment do
    ActiveRecord::Base.establish_connection BaseModel.connection_config
    ActiveRecord::Migrator.migrate('db/migrate/')
  end

  desc 'drop database'
  task drop: :environment do
    connection_config = BaseModel.connection_config
    ActiveRecord::Base.establish_connection connection_config.merge('database' => 'postgres')
    ActiveRecord::Base.connection.drop_database connection_config[:database]
  end

现在,如果您在项目中执行 rake -T,您应该能够看到您对 rake 任务的描述,而不是默认的。当您 运行 它们时,它将 运行 用于默认数据库和辅助数据库的 db:create、db:migrate 和 db:drop。希望这对您有所帮助!