我需要在不同的 Rails 模型中使用不同的数据库连接。有没有一种不太 hacky 的方法来做到这一点?
任何链接或搜索关键字都很棒 :)
最佳答案
将新部分添加到您的 database.yml
例如
other_development:
adapter: mysql
database: otherdb_development
username: root
password:
host: localhost
other_production:
adapter: mysql
database: otherdb_production
username: root
password:
host: localhost
在lib/other_database.rb
中添加一个类
class OtherDatabase < ActiveRecord::Base
establish_connection "other_#{RAILS_ENV}"
end
然后对于每个不在 OtherDatabase
默认数据库子类中的模型,例如:
class MyModel < OtherDatabase
# my model code...
end
关于ruby-on-rails - 我如何在具有事件记录的 Rails 中使用两个不同的数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1226182/