0

I'm following a tutorial to change the database depending on the subdomain, the subdomain must be the name of an existing database to which the system will connect as shown in this tutorial at 15:30 minute and works quite well, The problem comes when the system is accessed with a subdomain whose database does not exist, showing me the following error: Cannot open database "another_database" requested by the login. The login failed and displaying the error does not allow access to the system, regardless of whether it is accessed with the name of an existing database in the subdomain unless the rails server is restarted.

This is my code in my ApplicationController:

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  before_action :connect_to_database


  def connect_to_user_database(name)
    config = ActiveRecord::Base.configurations["development"].merge("database" => "#{name}")
    ActiveRecord::Base.establish_connection(config)
    #auth = name
    #raise auth.to_yaml #podemos ver los datos que nos ofrece el parametro
  end


  private

  def connect_to_database
    connect_to_user_database(request.subdomains(0).first)
  end

end
Ing.LuisC
  • 27
  • 7

1 Answers1

0

Using something like what is done in this answer https://stackoverflow.com/a/25592558/8088139 build a catch situation to fail gracefully if the database doesn't exist

something like

def connect_to_user_database(name)
  config = ActiveRecord::Base.configurations["development"].merge("database" => "#{name}")
  ActiveRecord::Base.establish_connection(config)
rescue ActiveRecord::NoDatabaseError
  clear_cache!
  #set response to forbidden
  #log the failure
end

EDIT: added clear_cache! to NoDatabaseError rescue

Michael Gorman
  • 1,077
  • 7
  • 13