Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a catch-all route in Ruby on 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.

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.

like image 899
at. Avatar asked Oct 14 '13 20:10

at.


People also ask

How do I see all routes in Rails?

TIP: If you ever want to list all the routes of your application you can use rails routes on your terminal and if you want to list routes of a specific resource, you can use rails routes | grep hotel . This will list all the routes of Hotel.

What are RESTful routes in Rails?

In Rails, a RESTful route provides a mapping between HTTP verbs, controller actions, and (implicitly) CRUD operations in a database. A single entry in the routing file, such as. map.resources :photos. creates seven different routes in your application: HTTP verb.

What is namespace route in Rails?

Namespaces are used to organize a group of controllers. For example, you may wish to organize a group of controllers that are only accessible by the admin of your app, under the Admin:: namespace.


1 Answers

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

like image 169
TheAshwaniK Avatar answered Oct 12 '22 22:10

TheAshwaniK