Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use match rather than get when routing in Rails?

In the Ruby on Rails 3 tutorial, the code uses:

match '/signup',  :to => 'users#new'
match '/signin',  :to => 'sessions#new'
match '/signout', :to => 'sessions#destroy'

match '/contact', :to => 'pages#contact'
match '/about',   :to => 'pages#about'
match '/help',    :to => 'pages#help'

rather than

get '/signup',  :to => 'users#new'
get '/signin',  :to => 'sessions#new'
get '/signout', :to => 'sessions#destroy'

get '/contact', :to => 'pages#contact'
get '/about',   :to => 'pages#about'
get '/help',    :to => 'pages#help'

even though all the routes only want the HTTP GET verb. Why not use get (or :via => [:get] on match) and limit the routing action as a matter of practice?

like image 935
George Shaw Avatar asked Dec 23 '11 18:12

George Shaw


People also ask

What is match in Rails routes?

Rails routes are matched in the order they are specified, so if you have a resources :photos above a get 'photos/poll' the show action's route for the resources line will be matched before the get line. To fix this, move the get line above the resources line so that it is matched first.

What are RESTful routes in Rails?

3.2 CRUD, Verbs, and Actions 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 in Rails routes?

This is the simple option. When you use namespace , it will prefix the URL path for the specified resources, and try to locate the controller under a module named in the same manner as the namespace.

How do I find 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.


1 Answers

I would consider it a best practice to use get [...] instead of match. As you already mentioned correctly, match will create both GET and POST routes. Why create them if you do not need them?

Using the correct matchers (get or post) keeps your routes clean and helps prevent unwanted behavior of your application. The latter point is true especially for POST routes, where you do not want to accidentially put a GET request link on your webpage that can be followed by search bots.

Update [2013-05-12]: From Rails 4.0 onwards you are now required to explicitly specifiy the request method.

like image 133
emrass Avatar answered Oct 04 '22 14:10

emrass