2016-05-23 58 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