【问题标题】:Rails route with arbitrary number of slashes带有任意数量斜线的 Rails 路由
【发布时间】:2014-07-27 02:59:05
【问题描述】:

我有一个基于 http://guides.rubyonrails.org/routing.html#advanced-constraints 的自定义路由,它根据输入的 url 检查重定向。

例如 /site 可能会重定向到 /mysite

代码如下:

class RedirectCheck
  def initialize
    @redirects = Redirect.all_from_paths
  end

  def matches?(request)
    @redirects.include?(request[:path])
  end
end

MyApp::Application.routes.draw do
  get ":path" => 'redirects#show', constraints: RedirectCheck.new
end

Redirect.all_from_paths 基本上是一个模型方法,它返回一个包含所有已接受路由的数组,然后 'redirects#show' 进行实际重定向。

现在我的问题是路线..

get ":path" => 'redirects#show', constraints: RedirectCheck.new

..不接受带有斜杠的路径

例如,我无法添加 /go/some/ 这样的路径,我的重定向路由无法识别它

如何更改此行,使其接受带有任意数量斜杠的任何路径并将其作为 params[:path] 传递给 'redirects#show'?

【问题讨论】:

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


    【解决方案1】:

    你想要的是:

    get "*path", to: 'redirects#show', constraints: RedirectCheck.new
    

    Rails routing guide 上还有许多其他示例。

    【讨论】:

    • 这很好,但如果你能添加更多细节会更好 - 不要忘记这个网站上的所有菜鸟都希望了解为什么会这样。或许可以为他们解释一下* 的属性:)
    • 好吧,现在我因为不尝试而感到愚蠢:)
    猜你喜欢
    • 2013-06-29
    • 1970-01-01
    • 1970-01-01
    • 2011-05-15
    • 2012-03-07
    • 1970-01-01
    • 2013-10-09
    • 2020-03-26
    • 1970-01-01
    相关资源
    最近更新 更多