How to create a catch-all route in Ruby on Rails?

為{幸葍}努か 提交于 2019-11-27 18:02:59

问题


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.

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

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.


回答1:


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

UPDATE:

#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!'

And

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

More info here: https://gist.github.com/Sujimichi/2349565




回答2:


This should work

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


来源:https://stackoverflow.com/questions/19368799/how-to-create-a-catch-all-route-in-ruby-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!