问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/8619449/why-use-match-rather-than-get-when-routing-in-rails