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

at.*_*at. 10 routes ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2 ruby-on-rails-4

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

match '*', to: 'subdomain_controller#show', constraints: {subdomain: /.+\.users/}
Run Code Online (Sandbox Code Playgroud)

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

使用Ruby on Rails 3.2,但准备升级到4.0.

更新:'*path'似乎工作.但是,我遇到的问题是每当文件存在于我的public目录中时,Rails就会呈现它.

The*_*niK 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!'
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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

  • Rails 4接受匹配,但您还需要指定HTTP方法.Catch-all重定向到root是`match"*path",to:redirect('/'),via :: all` (2认同)

ush*_*sha 0

这应该有效

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