ruby-on-rails - 我如何在具有事件记录的 Rails 中使用两个不同的数据库?

标签 ruby-on-rails ruby activerecord

我需要在不同的 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/

相关文章:

ruby-on-rails - Rails 4 中没有计数的复数

mysql - Rails - 在组、用户、所有者、成员协会方面遇到困难

ruby-on-rails - Rails 记录不关联

ruby-on-rails - 如何将 rails devise sign_in 路径设置为根 url

ruby-on-rails - ActionMailer 无法在本地主机上使用 gmail 或适用于 Rails 3.1.3 的谷歌应用程序

ruby-on-rails - rails 3 : How to “redirect_to” in Ajax call when form submited using html

ruby-on-rails - 类似于 Rails 的桌面应用程序框架

ruby - 嵌套液体自定义标签 block

ruby-on-rails - 覆盖 Controller 中的 protect_from_forgery 策略

ruby - 使用 gsub 在字符之间插入空格 - Ruby