问题:我有多个必须连接的数据库,具体取决于从一开始就选择的服务器。如果我有一个具有用户类关联的客户端表,我可以很好地连接到其中一个数据库并查询客户端,但如果我这样做了,@clients.userclasses
我会收到一条错误消息,指出表用户类不存在,因为它恢复到原始数据库。
下面的代码:
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