如何在Ruby on Rails中创建一个catch-all路由?

时间:2013-10-14 20:32:52

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2 routes ruby-on-rails-4

我希望所有满足特定约束的请求都转到特定的控制器。所以我需要一条全能的路线。如何在Rails中指定?是这样的吗?

match '*', to: 'subdomain_controller#show', constraints: {subdomain: /.+\.users/}

真的会抓住所有可能的路线吗?即使有很多嵌套目录,重要的是没有任何漏洞。

使用Ruby on Rails 3.2,但已准备好升级到4.0。

更新 '*path'似乎有效。但是,我遇到的问题是,当我的public目录中存在该文件时,Rails会将其呈现。

2 个答案:

答案 0 :(得分:18)

我认为你需要对这种方法进行微调,但你明白了这一点:

更新:

#RAILS 3
#make this your last route.
match '*unmatched_route', :to => 'application#raise_not_found!'

#RAILS 4, needs a different syntax in the routes.rb. It does not accept Match anymore.
#make this your last route.
get '*unmatched_route', :to => 'application#raise_not_found!'

class ApplicationController < ActionController::Base

...
#called by last route matching unmatched routes.  
#Raises RoutingError which will be rescued from in the same way as other exceptions.
def raise_not_found!
    raise ActionController::RoutingError.new("No route matches #{params[:unmatched_route]}")
end
...

end

此处有更多信息:https://gist.github.com/Sujimichi/2349565

答案 1 :(得分:0)

这应该有效

Calamas::Application.routes.draw do
  get '*path', to: 'subdomain_controller#show',constraints: lambda { |request| request.path =~ /.+\.users/ }
end