Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same Rails 4 routes for GET and POST requests

In Rails 3 Match used to point to an action for both "GET" and "POST" and other type of requests.

match "user/account" => user#account 

Now this will point to account action of user's controller for both GET and POST requests. As in Rails 4 "match" has been deprecated, can we create same route for GET and POST in Rails 4?

like image 683
Adnan Ali Avatar asked Sep 13 '13 07:09

Adnan Ali


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.

How many types of routes are there in Rails?

Rails RESTful Design which creates seven routes all mapping to the user controller. Rails also allows you to define multiple resources in one line.

What is the difference between member and collection in Rails route?

A member route will require an ID, because it acts on a member. A collection route doesn't because it acts on a collection of objects. Preview is an example of a member route, because it acts on (and displays) a single object.


2 Answers

From the match documentation, you can use match as long as you have via:

match "user/account" => "user#account", as: :user_account, via: [:get, :post] 

Edit: Added a as: parameter so that it will be accessible via a url helper. user_account_path or user_account_url in this case.

like image 160
Tim Dorr Avatar answered Sep 18 '22 00:09

Tim Dorr


On routes, the match method will no longer act as a catch-all option. You should now specify which HTTP verb to respond to with the option :via

Rails 3.2

match "/users/:id" => "users#show" 

Rails 4.0

match "/users/:id" => "users#show", via: :get 

or specify multiple verbs

match "/users" => "users#index", via: [:get, :post] 

Another option for better Rails 3.2 compatibility is to just specify your actions with explicit get, post, or any other HTTP verb. With this option, you still get your code running today and future proof it for the upgrade.

Rails 3.2 and 4.0 compatible

get "/users/:id" => "users#show" 

multiple verbs

get "/users" => "users#index" post "/users" => "users#index" 
like image 36
Ch Zeeshan Avatar answered Sep 21 '22 00:09

Ch Zeeshan