ActiveRecord迁移多个Postgresql数据库

时间:2019-06-26 06:54:11

标签: ruby-on-rails activerecord

我有多个数据库。主数据库human_development的所有迁移都运行良好。第二个数据库称为动物,迁移失败。

database.yml:

default: &default
  adapter: postgresql
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000
  encoding: unicode
  user: blah

development:
  <<: *default
  database: human_development

animals:
  <<: *default
  database: animals

迁移失败:

class SomeTable < ActiveRecord::Migration[5.2]
  def change
    ActiveRecord::Base.establish_connection("animals")

    create_table :some_table, id: :uuid do |t|
      t.string :type
      t.timestamps
    end

    ActiveRecord::Base.establish_connection(Rails.env)
  end
end

我还尝试了以下无效的方法:

  1. def connection
      ActiveRecord::Base.establish_connection("animals").connect
      #ActiveRecord::Base.establish_connection("animals".to_sym).connect
    end
    
  2. 在更改之外建立连接

  ActiveRecord::Base.establish_connection("animals").connect
  # also tried with to_sym

如果运行“ rails db:migrate”,将数据库名称作为字符串传递,则会出现以下错误:

rake aborted!
ActiveRecord::AdapterNotSpecified: database configuration does not specify adapter
.../db/migrate/2019_some_tables.rb:2:in

并且如果我将rails db:migrateto_sym一起运行,则会出现以下错误:

-- create_table(:some_table, {:id=>:uuid})
rake aborted!
ActiveRecord::StatementInvalid: PG::ConnectionBad: connection is closed: SELECT pg_advisory_unlock


Caused by:
PG::ConnectionBad: connection is closed


Caused by:
StandardError: An error has occurred, this and all later migrations canceled:

PG::ConnectionBad: connection is closed: ROLLBACK


Caused by:
ActiveRecord::StatementInvalid: PG::ConnectionBad: connection is closed: ROLLBACK


Caused by:
PG::ConnectionBad: connection is closed

2 个答案:

答案 0 :(得分:1)

所有数据库的迁移文件都应该相同

class SomeTable < ActiveRecord::Migration[5.2]
  def change    
    create_table :some_table, id: :uuid do |t|
      t.string :type
      t.timestamps
    end
  end
end

然后在控制台中运行

# for the main db
rails db:migrate

# for the animals db
RAILS_ENV=animals rails db:migrate

答案 1 :(得分:1)

@Eyeslandic非常感谢,这很有帮助!

以防其他任何人遇到相同的问题。看起来Rails 6将为此提供更好的解决方案,但与此同时,这是我必须进行的其他更改:

  1. database.yml:我想将迁移保留在单独的文件夹中:
├── db
│   ├── migrate
│   ├── schema.rb
│   └── seeds.rb
├── animals_db
│   └── migrate
animals:
  <<: *default
  database: animals
  migrations_paths: animals_db/migrate
  1. 创建新环境:config/environments/animals.rb
  2. 更改config/secrets.yml以包括新环境
  3. 生成机密:RAILS_ENV=animals rake secret
  4. 将机密保存为.env文件或将其导出
  5. 创建数据库:rails db:create RAILS_ENV=animals
  6. 在animals_db中创建迁移,但这是要抓住的地方。我必须在def change
  7. 中添加以下内容
def change
  create_table :some_table, id: :uuid do |t|
    enable_extension "uuid-ossp"
    enable_extension "pgcrypto"
    t.string :type
    t.timestamps
  end
end
  1. 运行迁移:rails db:migrate RAILS_ENV=animals

您可能还需要更改config/cable.yml以包括新环境

希望这会有所帮助。期待看到Rails 6将如何改善这一点