如何在Ruby on Rails中创建一个包罗万象的路线? [英] How to create a catch-all route in Ruby on Rails?

查看:76
本文介绍了如何在Ruby on Rails中创建一个包罗万象的路线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让所有满足特定约束的请求都转到特定的控制器。所以我需要一条通吃的路线。如何在Rails中指定呢?

I want to have all requests that satisfy a certain constraint to go to a specific controller. So I need a catch-all route. How do I specify that in Rails? Is it something like this?

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

会真正抓住所有可能的路线吗?重要的是,即使存在许多嵌套目录,也不要漏过。

Will that really catch all possible routes? It's important that none slip through even if there are many nested directories.

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

Using Ruby on Rails 3.2, but ready to upgrade to 4.0.

更新 '* path'似乎有效。但是,我遇到的问题是只要文件存在于我的 public 目录中,Rails就会渲染该文件。

UPDATE: '*path' seems to work. However, the issue I'm running into is whenever the file exists in my public directory, Rails renders that instead.

推荐答案

我认为您需要对此方法进行一些细微调整,但是您明白了:

I think you need minor tweaks in this approach but you get the point:

更新:

#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

这篇关于如何在Ruby on Rails中创建一个包罗万象的路线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆