【问题标题】:Error trying to change database尝试更改数据库时出错
【发布时间】:2017-11-01 20:42:18
【问题描述】:

我正在按照教程根据子域更改数据库,子域必须是系统将连接到的现有数据库的名称,如this tutorial 在 15:30 分钟所示,并且运行良好,当使用数据库不存在的子域访问系统时出现问题,显示以下错误: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

【问题讨论】:

  • 为了安全和避免错误,您应该在connect_to_database之前检查子域是否有效。
  • @wesley6j 感谢您的回答,但是如何检查数据库是否存在?
  • 如果您有想要使用的子域列表,请将数组保存在代码库或配置文件中的某个位置。
  • 你能rescue StandardError render file: "#{Rails.root}/public/404", layout: true, status: :not_found end
  • @wesley6j 非常感谢,它成功了

标签: ruby-on-rails ruby database ruby-on-rails-4


【解决方案1】:

使用类似于此答案中所做的事情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 救援

【讨论】:

  • 感谢回复,我粘贴了代码,但仍然显示相同的错误
  • 尝试在救援案例“clear_cache!”中运行此命令用这个编辑答案
  • 我放置了您的代码并启动了 rails 服务器,但是当我第一次输入一个不存在的数据库时输入现有数据库的名称时仍然出现相同的错误。
  • 然后我会建议 wesley6j 的建议,创建可接受子域的白名单,如果传入域不在白名单中,甚至不尝试数据库连接
  • 谢谢,我会选择那个选项。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-05
  • 2014-06-09
  • 1970-01-01
  • 1970-01-01
  • 2021-01-28
  • 2021-07-01
相关资源
最近更新 更多