我正在用这个apartment ruby gem 。

我已经在application.rb文件中添加了它:

config.middleware.use 'Apartment::Elevators::Subdomain'

当我尝试在浏览器URL'test.domain.local:3000'中命中该问题时,在PostgreSQL中不存在子域'test'模式,我看到此错误
Apartment::SchemaNotFound (One of the following schema(s) is invalid: test, "public")

我知道这是gem的正常行为,但想捕获此异常并将用户重定向到其他页面,我该怎么做?

最佳答案

这是我所做的:

在lib/rescued_apartment_middleware.rb下创建文件

module RescuedApartmentMiddleware
  def call(*args)
    begin
      super
    rescue Apartment::TenantNotFound
      Rails.logger.error "ERROR: Apartment Tenant not found: #{Apartment::Tenant.current.inspect}"
      return [404, {"Content-Type" => "text/html"}, ["#{File.read(Rails.root.to_s + '/public/404.html')}"] ]
    end
  end
end

然后将以下行添加到您的Apartment初始化程序文件中:
require 'rescued_apartment_middleware'

Rails.application.config.middleware.use 'Apartment::Elevators::Subdomain'
Apartment::Elevators::Subdomain.prepend RescuedApartmentMiddleware

这就像一个魅力! (使用ruby 2.1和Rails 4.1进行测试)

10-08 04:26