我有多个数据库。主数据库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
我还尝试了以下无效的方法:
def connection
ActiveRecord::Base.establish_connection("animals").connect
#ActiveRecord::Base.establish_connection("animals".to_sym).connect
end
在更改之外建立连接
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:migrate
与to_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
答案 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将为此提供更好的解决方案,但与此同时,这是我必须进行的其他更改:
├── db
│ ├── migrate
│ ├── schema.rb
│ └── seeds.rb
├── animals_db
│ └── migrate
animals:
<<: *default
database: animals
migrations_paths: animals_db/migrate
config/environments/animals.rb
config/secrets.yml
以包括新环境RAILS_ENV=animals rake secret
rails db:create RAILS_ENV=animals
def change
def change
create_table :some_table, id: :uuid do |t|
enable_extension "uuid-ossp"
enable_extension "pgcrypto"
t.string :type
t.timestamps
end
end
rails db:migrate RAILS_ENV=animals
您可能还需要更改config/cable.yml
以包括新环境
希望这会有所帮助。期待看到Rails 6将如何改善这一点