我正在遵循一个教程来改变数据库取决于子域,子域必须是现有数据库的名称,系统将连接到15:30分钟,如this tutorial所示,并且工作得很好,当访问系统的子域的数据库不存在时,问题就来了,显示以下错误:Cannot open database "another_database" requested by the login. The login failed和显示错误不允许访问系统,无论它是否是使用子域中现有数据库的名称访问,除非重新启动rails服务器。
这是我在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发布于 2017-06-01 05:50:53
使用与此答案类似的方法https://stackoverflow.com/a/25592558/8088139构建一个捕获情况,以便在数据库不存在的情况下正常失败
就像这样
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编辑:添加clear_cache!拯救NoDatabaseError
https://stackoverflow.com/questions/44295006
复制相似问题