Rails以任意数量的斜杠进行路由

时间:2014-06-05 23:09:17

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

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

例如/ 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基本上是一个模型方法,它返回一个包含所有接受路由的数组,然后'重定向#show'进行实际的重定向。

现在我的问题是路线..

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

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

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

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

1 个答案:

答案 0 :(得分:1)

你想要的是:

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

Rails routing guide还有很多其他例子。