Rails 3.2具有相同型号名称的多个数据库连接

时间:2014-02-05 20:49:41

标签: ruby-on-rails database ruby-on-rails-3 multiple-databases

关于在rails中创建与多个数据库的多个连接,有许多问题和答案:

https://stackoverflow.com/a/7480330/2120023

https://stackoverflow.com/a/6305540/2120023

来自外部stackoverflow的示例:http://ilikestuffblog.com/2012/09/21/establishing-a-connection-to-a-non-default-database-in-rails-3-2-2/

但是我还没有找到一个在使用两个数据库中出现的模型时都能正常工作的解决方案。

如果我的默认数据库有一个表titles而我的Other数据库有一个表titles,我如何访问另一个数据库的标题模型?

title.rb

class Title < ActiveRecord::Base
end

othertitle.rb

class Other < ActiveRecord::Base
  self.abstract_class = true
  establish_connection "other_#{Rails.env}"
end

class OtherTitle < Other
end

我无法使用上述内容,因为我收到了这个错误(编辑:为了清楚起见,在db只有一个other_titles表中没有titles表 - &gt;编辑2:如果我确实创建了other_titles数据库中的Other表,一切都运行良好但不能帮助我访问titles表。):

ActiveRecord::StatementInvalid: Mysql2::Error: Table 'other.other_titles' doesn't exist: SHOW FULL FIELDS FROM `other_titles`

我也无法使用class Title < Other,因为我收到TypeError: superclass mismatch for class Title错误。

database.yml

development:
  adapter: mysql2
  encoding: utf8
  database: db_dev
  pool: 5
  username: xxxx
  password: xxxx
  socket: /var/lib/mysql/mysql.sock

production:
  adapter: mysql2
  encoding: utf8
  database: db
  pool: 5
  username: xxxx
  password: xxxx
  socket: /var/lib/mysql/mysql.sock


other_development:
  adapter: mysql2
  encoding: utf8
  database: other_dev
  pool: 5
  username: xxxx
  password: xxxx
  socket: /var/lib/mysql/mysql.sock

other_production:
  adapter: mysql2
  encoding: utf8
  database: other
  pool: 5
  username: xxxx
  password: xxxx
  socket: /var/lib/mysql/mysql.sock 

1 个答案:

答案 0 :(得分:1)

我找到了答案,这很简单:

class OtherTitle < Other
  self.table_name='titles'
end

参考此处:

Efficient way to pull data from second database?

在这里:

Cannot connect to two postgres databases in rails 3.2.