这是我的用例
在某些模型中,用户在不同的主机上连接不同的数据库。因此,使用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 })我的问题是,我如何设置:主机,从charges_controller.rb不良?establish_connection方法中的所有其他参数都是“固定的”。
尝试使用应用程序控制器中的before_filter将值设置为ip_address无效。也尝试使用初始化的收费模式(虽然一个坏的想法),但没有任何效果。*主机,返回零
谢谢
发布于 2016-05-23 15:17:06
删除虚拟属性attr_accessor :host中的“c”,然后在使用这些参数传递给模型之前,在控制器中将该值插入到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更新
可以在模型中设置此方法,然后在控制器中新创建的对象上引用该方法:
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 })
endhttps://stackoverflow.com/questions/37393988
复制相似问题