如何在rails应用程序中配置多个数据库源

时间:2012-06-25 16:52:19

标签: ruby-on-rails

我想为某个环境(比如暂存或生产)配置2个数据库实例。默认rails新应用程序只提供单个数据库实例,如何配置2个数据库实例。

1 个答案:

答案 0 :(得分:1)

您可以复制并覆盖现有配置之一,例如开发。并根据需要重命名,在database.yml:

development:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: 
  pool: 5
  username: root
  password: 
  host: localhost


new_database:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: 
  pool: 5
  username: root
  password: 
  host: localhost

然后,在为此新连接创建的模型中,将以下方法添加到模型中,例如:

class Document < ActiveRecord::Base
  self.table_name = "document"   # this allows you to hide a non comforming table name behind the rails model it is NOT necessary for establish_connection to work
  self.establish_connection "new_database"  # notice there is no = when setting this value, strange, I know.
end