0
問題:我必須連接多個數據庫,具體取決於從一開始就選擇的服務器。如果我有一個具有用戶類關聯的客戶端表,我可以連接到其中一個數據庫並查詢客戶端,但是如果我做了@clients.userclasses
,我得到一個錯誤,指出表userclasses不存在,因爲它恢復爲原始數據庫。下面establish_connection沒有引入模型關聯
代碼:
class Connection < ActiveRecord::Base
self.abstract_class = true
end
class Client < Connection
has_many :userclasses, :dependent => :destroy
end
class Userclass < Connection
belongs_to :client
self.table_name = "userclasses"
end
class ClientsController < ApplicationController
before_filter :set_server
def show
@client = Client.find(params[:id])
respond_to do |format|
format.html{ render html: @client}
format.xml { render xml: @client }
end
end
private
def set_server
@server = Server.find(params[:server_id])
unless @server.nil? or @server.database.nil?
Client.establish_connection(ActiveRecord::Base.configurations["#{@server.database}"])
end
end
end