3

我正在我正在制作的应用程序中尝试 Rails 4.0 中的多个数据库。基于此:Connecting Rails 3.1 with Multiple Databaseshttp://api.rubyonrails.org/classes/ActiveRecord/Base.html

我能够创建一些使用不同连接的模型,但是,当我尝试从抽象类继承连接以保持我的代码干燥时,Rails 4.0 自动假定我正在尝试执行单表继承查询信息,然后抛出一个表不存在的 Mysql::Error。

以下是一些代码片段,可以帮助我了解我当前的状态基类:

Class Mps < ActiveRecord::Base
  self.abstract_class = true
  establish_connection "mps"
end

儿童班:

Class TblAdmVsl < Mps
  self.table_name = "tbladmvsl"
end

有什么办法可以解决这个问题,因为我想让我的代码尽可能干燥。以下是我在 Rails 控制台中尝试此操作时收到的错误

2.0.0-p247 :005 > TblAdmVsl.first
  TblAdmVsl Load (4.5ms)  SELECT `tbladmvsl`.* FROM `tbladmvsl` ORDER BY `tbladmvsl`.`id` ASC LIMIT 1
  Mysql::Error: Table 'mps2_tbl.mps' doesn't exist: SHOW FULL FIELDS FROM `mps`
  ActiveRecord::StatementInvalid: Mysql::Error: Table 'mps2_tbl.mps' doesn't exist: SHOW     FULL FIELDS FROM `mps`
        from /home/maru/.rvm/gems/ruby-2.0.0-p247/gems/activerecord-4.0.0/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:286:in `query'
        from /home/maru/.rvm/gems/ruby-2.0.0-p247/gems/activerecord-4.0.0/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:286:in `block in execute'
4

1 回答 1

1

尝试这个:

Class Mps < ActiveRecord::Base
  self.abstract_class = true
  self.table_name = "mps"
  establish_connection self.table_name
end

class TblAdmVsl < Mps
  self.table_name = "tbladmvsl"
end

我不确定是否有仅通过数据库名称建立连接的功能,也许您在某处覆盖此功能,但标准解决方案是连接传递配置(database.yml 的副本)文件:

new_config = ActiveRecord::Base.configurations[Rails.env].clone
new_config['database'] = "another_database_name"
ActiveRecord::Base.remove_connection #optional if you need to remove current connection
ActiveRecord::Base.establish_connection new_config
于 2013-09-18T08:41:47.347 回答