2016-05-23 46 views
0

這是我的使用案例,使用多個數據庫軌道4

在某些模型上,用戶連接到不同主機上的不同數據庫。使用establish_connection因此,

#charge.rb 
cattr_accessor :ip_address 
ActiveRecord::Base.establish_connection({:adapter => "postgresql", :database => Rails.application.config.database_name, :host => ip_address, 
             :username => Rails.application.config.database_user, :password => Rails.application.config.database_password }) 

我的問題,我該如何設置:主機,dynimically從charges_controller.rb? establish_connection方法中的每個其他參數都是「固定的」。

嘗試使用應用程序控制器中的before_filter將值設置爲ip_address無濟於事。還嘗試使用初始化充電模型(雖然是一個壞主意),無濟於事。 :主機,返回nil

謝謝

回答

0

在你的虛擬屬性​​去掉「C」,然後傳遞給那些PARAMS模型前在控制器該值插入您的PARAMS散一會兒。例如:

在典型的控制器,你會碰到這樣的:

def create 
@charge = Charge.create(charge_params) 
@charge.connect_to_proper_host(host) 
end 

private 

def charge_params 
    params.require(:charge).permit(:at1 , :some_other_att, :host) 
end 

UPDATE

您可以在模型中設置此方法,然後引用它在新創建的對象上你控制器:

def connect_to_proper_database(host) 
     self.host = host 
     #Note, You don't need to define self.host if you dont plan on reusing this variable throughout other methods in the model and can instead reference it by simply "host" in that case. 
    ActiveRecord::Base.establish_connection({:adapter => "postgresql", :database => Rails.application.config.database_name, :host => self.host, :username => Rails.application.config.database_user,:password => Rails.application.config.database_password }) 
    end 
+0

謝謝,但得到「參數丟失或值爲空」錯誤... – dev

+0

Sorr y離開了一步,看看更新 – bkunzi01