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

后端 未结 2 1832
青春惊慌失措
青春惊慌失措 2020-12-16 18:33

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 li

相关标签:
2条回答
  • 2020-12-16 19:03

    This should work

    Calamas::Application.routes.draw do
      get '*path', to: 'subdomain_controller#show',constraints: lambda { |request| request.path =~ /.+\.users/ }
    end
    
    0 讨论(0)
  • 2020-12-16 19:17

    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

    0 讨论(0)
提交回复
热议问题