简体   繁体   中英

How to configure multiple database sources in a rails application

I would like to configure 2 database instances for a certain environment (say staging or production). The default rails new application just provides a single database instance how do I configure 2 database instances.

You can copy and past one of your existing configurations such as development. and rename it as you want so, in the 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

Then in the models you create for this new connection add the following methods to the model, for example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM