关于在rails中创建到多个数据库的多个连接,有许多问题和答案:
https://stackoverflow.com/a/7480330/2120023
https://stackoverflow.com/a/6305540/2120023
来自外部堆栈溢出的示例:http://ilikestuffblog.com/2012/09/21/establishing-a-connection-to-a-non-default-database-in-rails-3-2-2/
但我还没有找到一个解决方案,当使用出现在两个数据库中的模型时。
如果我的默认数据库有一个表titles,而我的Other db有一个表titles,我如何访问其他数据库的标题模型?
title.rb
class Title < ActiveRecord::Base
endothertitle.rb
class Other < ActiveRecord::Base
self.abstract_class = true
establish_connection "other_#{Rails.env}"
end
class OtherTitle < Other
end我不能使用上面的错误,因为我得到了这个错误(编辑:为了清楚起见,在两个数据库中都没有other_titles表,只有一个titles表->编辑2:如果我确实在Other数据库中创建了一个other_titles表,那么一切都可以很好地工作,但这并不能帮助我访问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 发布于 2014-02-06 14:29:05
我找到了答案,答案很简单:
class OtherTitle < Other
self.table_name='titles'
end在此引用:
Efficient way to pull data from second database?
在这里:
https://stackoverflow.com/questions/21588192
复制相似问题