2016-05-23 3 views
0

これは私の使用例です複数のデータベース・レールを使用する4

一部のモデルでは、異なるホスト上の異なるデータベースに接続します。ホストを、dynimically charges_controller.rbから:

#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 }) 

私の質問は、どのように私は設定することができ、これestablish_connectionを使用していますか? establish_connectionメソッドの他の引数はすべて「固定」です。

アプリケーションコントローラでbefore_filterを使用して、値をip_addressに設定して無駄にすることを試みました。また、充電モデル(ただし、悪い考えでも)で初期化を使用して無駄にしてみました。 :ホストは、

答えて

0

が仮想属性​​で「C」を削除して、コントローラにいる間、これらのparamsをモデルに渡す前に、あなたのparamsハッシュに値を挿入ありがとう

nilを返します。例えば:あなたのモデルでは、この方法を設定し、自分の中に新しく作成されたオブジェクトの上にそれを参照することができます

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

おかげで、しかし、「paramは存在しないか、値が空である」エラーを取得... – dev

+0

Sorrステップを省き、アップデートを見てください – bkunzi01

関連する問題