Dynamic connection

Yes, there is. establish_connection and not set_table_name is the answer. I’ve been down both routes and establish_connection is much lighter on the necessary code than set_table_name.

RSL

Here’s what I did. Site model is in the default db and contains a db_name attribute which holds the name of the db for that site. In Site…

DB_PREFIX = “whatever_”

def ensure_connection
[Attachment, Document, Category, Tag].each do |klass|

unless ActiveRecord::Base.configurations.has_key? db_name
  config = ActiveRecord::Base.configurations[RAILS_ENV]
  ActiveRecord::Base.configurations[db_name] = {
    :adapter => "mysql",

    :host => config["host"],
    :username => config["username"],
    :password => config["password"],
    :database => "#{DB_PREFIX}#{db_name}"

  }
end
[Attachment, Category, Comment, Document, Tag, Source].each do |model|
  if model.connection.config[:database] != "#{DB_PREFIX}#{db_name}"
     model.establish_connection

db_name
# You have to do this manually…
model.connection.logger = RAILS_DEFAULT_LOGGER
end
end
end
end

and in my controllers that need to access that data just create a before_filter which calls Site#ensure_connections. Unless you’re on to something I wasn’t set_table_name is more trouble than it’s worth. Hope that helps.

RSL