如何在具有活动记录的rails中使用两个不同的数据库?

gus*_*ans 43 ruby activerecord ruby-on-rails

我需要在不同的Rails模型中使用不同的数据库连接.是不是有一种不那么黑的方式呢?

任何链接或搜索关键字都会很棒:)

mik*_*kej 114

添加新的部分到您的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
Run Code Online (Sandbox Code Playgroud)

添加一个类 lib/other_database.rb

class OtherDatabase < ActiveRecord::Base
  establish_connection "other_#{RAILS_ENV}"
end
Run Code Online (Sandbox Code Playgroud)

然后对于不在默认数据库子类中的每个模型,OtherDatabase例如:

class MyModel < OtherDatabase
   # my model code...
end
Run Code Online (Sandbox Code Playgroud)

  • 我需要在`lib/other_database.rb`中添加`self.abstract_class = true` (4认同)

pen*_*ger 13

我一直在使用以下连接到同一个应用程序中的2 db.我把它们放在lib文件夹中,因为那里的所有内容都已加载.

require 'active_record'

class OldDatabase < ActiveRecord::Base
  self.abstract_class = true
  establish_connection(
  :adapter  => 'mysql',
  :database => 'weather',
  :host     => 'localhost',
  :username => 'root',
  :password => 'password'
  )
end

class NewDatabase < ActiveRecord::Base
  self.abstract_class = true
  establish_connection(
  :adapter  => 'mysql',
  :database => 'redmine',
  :host     => 'localhost',
  :username => 'root',
  :password => 'password'
  )
end

class WeatherData < OldDatabase
end

class Board < NewDatabase
end
Run Code Online (Sandbox Code Playgroud)

希望有所帮助


nit*_*der 10

迈克是对的.然而,我确实写了一个宝石,使模型代码连接得更清洁,检查出来.


pen*_*sky 9

Rails 3.x的更新:

class MyModel < ActiveRecord::Base
  establish_connection "other_#{Rails.env}"
end
Run Code Online (Sandbox Code Playgroud)