I’m implementing a one database per subdomain app, which is pretty
simple using the before_filter described on the wiki:
http://wiki.rubyonrails.org/rails/pages/HowtoUseMultipleDatabases.
I just do this in my hijack_db method:
return unless request.subdomains.first
db_name = “#{request.subdomains.first}_#{RAILS_ENV}”
ActiveRecord::Base.establish_connection
(ActiveRecord::Base.configurations[RAILS_ENV].merge({ ‘database’ =>
db_name }))
My problem happens when someone hits a subdomain that doesn’t exist.
It tries to connect to a database that doesn’t exist and throws the
Mysql::Error 'Unknown database …" Then on the next request, before
it ever makes it to the ApplicationController, when it’s making a
connection to the database for the query cache, it tries to use the
last connection specification (the invalid one) and I just get the
unknown database error again before my hijack_db ever gets a chance to
connect to a good db. At that point, the app is “stuck” trying to
connect to the unknown db.
I have a fix for this but I’m wondering if it’s a hack or if it’s
something I should actually try submitting as a patch to Rails (I’ve
never contributed before).
My fix/hack is that I just wrap the connection method in
ConnectionPool in a begin/rescue and catch the unknown database error
and “revert” the database in the connection specification to the one
from database.yml so that (assuming the database.yml has a valid db)
the next request will succeed.
Anyone have any opinions on this?