Search code examples
ruby-on-railsmultiple-databases

establish_connection doesn't bring over model associations


Issue: I have multiple databases that I have to connect to depending on the server that is chosen from the start. If I have a client table that has an association of userclasses, I can connect to one of the databases fine and query clients, but if I do @clients.userclasses I get an error saying that the table userclasses doesn't exist because its reverting back to the original database.

Code below:

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

Solution

  • I ended up just switching the entire ActiveRecord connection to the one I needed, instead of trying to switch just the model I was using.

    def set_server
        @server = Server.find(params[:server_id])
        unless @server.nil? or @server.database.nil?
          ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations["#{@server.database}"])
        end
      end