ActiveRecord :: Base。Establishment_connection连接到错误的数据库

Joh*_*ohn 0 activerecord ruby-on-rails

我创建了一个连接到2个数据库的类:

class Production < ActiveRecord::Base
  ActiveRecord::Base.establish_connection(:production)
  self.abstract_class = true
  attr_accessor
end

class Backup < ActiveRecord::Base
  ActiveRecord::Base.establish_connection(:backup)
  self.abstract_class = true
  attr_accessor
end

class RepairReport
  def init

  end

  def repair_now
    Production.table_name = "users"
    users = Production.all
    users.each do |user|
      puts "USER: #{user.last_name}"
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

这是database.yml

production:
  adapter: postgresql
  encoding: unicode
  database: test_eagle_development
  host: localhost
  pool: 296
  username: postgres
  password: password1
  template: template0

backup:
  adapter: postgresql
  encoding: unicode
  database: test_eagle_test
  host: localhost
  pool: 5
  username: postgres
  password: password1
  template: template0
Run Code Online (Sandbox Code Playgroud)

当我运行它时,它给出一个错误: ActiveRecord::AdapterNotSpecified: 'production' database is not configured. Available: ["development", "test"]

当我将更database.yml改为时developmenttest它可以工作,但是输出的用户来自另一个本地Rails应用程序中使用的另一个数据库。看来旧的连接仍在活动中?如何确定正确的数据库已连接?

更新:

现在这是我的更新database.yml和代码(请参见下文),但是它仍然连接到错误的数据库。当我删除developmenttest部分时,它返回:ActiveRecord::AdapterNotSpecified: 'development' database is not configured. Available: ["development_prod", "development_backup"],因此似乎在读正确的database.yml

development:
  adapter: postgresql
  encoding: unicode
  database: test_eagle_development
  host: localhost
  pool: 296
  username: postgres
  password: password1
  template: template0

test:
  adapter: postgresql
  encoding: unicode
  database: test_eagle_test
  host: localhost
  pool: 5
  username: postgres
  password: password1
  template: template0

development_prod:
  adapter: postgresql
  encoding: unicode
  database: test_eagle_development
  host: localhost
  pool: 296
  username: postgres
  password: password1
  template: template0

development_backup:
  adapter: postgresql
  encoding: unicode
  database: test_eagle_test
  host: localhost
  pool: 5
  username: postgres
  password: password1
  template: template0
Run Code Online (Sandbox Code Playgroud)

和代码:

  class Production < ActiveRecord::Base
    ActiveRecord::Base.establish_connection("#{Rails.env}_prod".to_sym)
    self.abstract_class = true
    attr_accessor
  end

  class Backup < ActiveRecord::Base
    ActiveRecord::Base.establish_connection("#{Rails.env}_backup".to_sym)
    self.abstract_class = true
    attr_accessor
  end
Run Code Online (Sandbox Code Playgroud)

chu*_*off 5

它必须establish_connection(:production)代替ActiveRecord::Base.establish_connection(:production)

:establish_connection必须调用每个特定类的方法,而不是父类的方法ActiveRecord::Base。配置父类没有任何意义)