首页 > 解决方案 > Ruby on Rails 使用 POST、PUT 方法从中间件重定向,它将我重定向到 Index 而不是 Show

问题描述

嘿,我正在尝试创建一个具有 3 种不同样式但使用相同控制器的管理门户

我想要并设法使我的 URL 如下所示:

www.localhost.com/admin
www.localhost.com/prefixA/admin
www.localhost.com/prefixB/admin

在每个请求中,我检测 URL 前缀并为其呈现相应的样式。

一切正常,他们都使用我想要的控制器。

我的路线如下所示:

# config.rb

Rails.application.routes.draw do
  extend AdminPortal
end

# config/routes/admin_portal.rb
module AdminPortal
  def self.extended(router)
    router.instance_exec do
      extend AdminRoutes
      extend PrefixAAdminRoutes
      extend PrefixBAdminRoutes
    end
  end
end

# config/routes/base_admin_routes.rb
module BaseAdminRoutes
  def self.extended(router)
    router.instance_exec do
      namespace :admin do
        # Routes goes here
      end
    end
  end
end

# config/routes/admin_routes.rb
module AdminRoutes
  def self.extended(router)
    router.instance_exec do
      extend BaseAdminRoutes
    end
  end
end


# config/routes/prefix_a_admin_routes.rb
module PrefixAAdminRoutes
  def self.extended(router)
    router.instance_exec do
      resource :prefix_a do
        extend BaseAdminRoutes
      end
    end
  end
end

# config/routes/prefix_b_admin_routes.rb
module PrefixBAdminRoutes
  def self.extended(router)
    router.instance_exec do
      resource :prefix_b do
        extend BaseAdminRoutes
      end
    end
  end
end

我现在的问题是如何一直保留某个前缀,如果我的 URL 在prefix_a我想在管理面板中移动时继续使用它,如果我正在使用prefix_b并打开选项卡,它会打开prefix_b附加到 URL 的链接。

我试图在中间件中这样做:

class AdminPanelSwitcher
  def initialize(app)
    @app = app
  end

  def call(env)
    request = Rack::Request.new(env)
    @status, @headers, _ = @app.call(env)

    if request.path.include? '/admin'
        env = portal_redirect env, request, PortalHelper::PREFIX_A
        env = portal_redirect env, request, PortalHelper::PREFIX_B
        _, _, @response = @app.call(env)
    end

    [@status, @headers, @response]
  end

  def portal_redirect(env, request, portal_prefix)
    if request.referer and request.referer.include? portal_prefix
      unless request.path.include? portal_prefix
        %w[ORIGINAL_FULLPATH PATH_INFO REQUEST_PATH REQUEST_URI].each do |req|
          env[req] = request.path.sub('admin', "#{portal_prefix}/admin")
        end
        @headers['Location'] = env['PATH_INFO']
        @status = 301
      end
    end
    env
  end
end

它只在GET请求中完美运行,但在POST, PUT, PATCH请求中,它的行为很奇怪,它会将我重定向到index而不是show一直,所以有比这更好的解决方案,或者我在中间件中遗漏了一些东西让我错过了它。

标签: ruby-on-railsrubyruby-on-rails-4puma

解决方案


推荐阅读