2012-06-25 38 views
0

我想爲特定環境(例如分段或生產)配置2個數據庫實例。默認的rails新應用程序只提供一個數據庫實例,我如何配置2個數據庫實例。如何在Rails應用程序中配置多個數據庫源

+0

你意味着你想使用不同的數據庫來存儲某些信息?或者你想將所有數據存儲在兩個不同的數據庫中?前者可以通過在'config/database.yml'中添加更多配置並在類文件中使用'establish_connection'來完成(參見http://pullmonkey.com/2008/4/21/ruby-on-rails-multiple-數據庫連接/)。後者...我真的不知道如何工作。 – MrTheWalrus

+0

我正在嘗試從2個不同的數據庫實例中爲UI的不同部分提取數據。兩個數據庫之間不會有任何關係。 – Joe

回答

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 
相關問題