【问题标题】:How to create a catch-all route in Ruby on Rails?如何在 Ruby on Rails 中创建一个包罗万象的路由?
【发布时间】:2013-10-22 12:34:43
【问题描述】:

我想让所有满足特定约束的请求都转到特定的控制器。所以我需要一条包罗万象的路线。我如何在 Rails 中指定它?是这样的吗?

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

这真的会捕获所有可能的路线吗?即使有许多嵌套目录,也不要漏掉,这一点很重要。

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

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

【问题讨论】:

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


【解决方案1】:

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

更新:

#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

【讨论】:

  • 这不适用于根路径或存在于public 目录中的路径。根路径没什么大不了的,我可以在我的路由文件中添加一个root to。但另一个问题我不知道如何克服。
  • 在 Rails 4 中它给了我错误:rake aborted!如果未指定 HTTP 方法,则不应在路由器中使用 match 方法。如果您想将您的操作公开给 GET 和 POST,请添加 via: [:get, :post] 选项。如果您想将您的操作公开给 GET,请在路由器中使用 get:而不是:匹配“controller#action”做:获取“controller#action”
  • 是的,我认为 Rails 4 需要在 routes.rb 中使用不同的语法。它不再接受匹配。得到 '*unmatched_route', :to => 'application#raise_not_found!'
  • Rails 4 确实接受匹配,但您还需要指定 HTTP 方法。重定向到根目录的包罗万象是match "*path", to: redirect('/'), via: :all
【解决方案2】:

这应该可以工作

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

【讨论】:

  • 没有试过这个,但看起来将:subdomain 作为路径可能会令人困惑?那么是路径约束还是子域约束呢?
  • 我之前的回答在你的情况下是行不通的。请参阅我的更新答案。此处的文档-> guides.rubyonrails.org/routing.html#advanced-constraints
  • 这不适用于根路径或存在于public 目录中的路径。根路径没什么大不了的,我可以在我的路由文件中添加一个根。但另一个问题我不知道如何克服。
猜你喜欢
  • 1970-01-01
  • 2016-04-22
  • 1970-01-01
  • 2016-08-20
  • 2011-04-02
  • 1970-01-01
  • 1970-01-01
  • 2011-10-13
  • 1970-01-01
相关资源
最近更新 更多