ruby GET 和 POST 请求的相同 Rails 4 路由

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18780252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 06:09:59  来源:igfitidea点击:

Same Rails 4 routes for GET and POST requests

rubyruby-on-rails-3routesruby-on-rails-4

提问by Adnan Ali

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

在 Rails 3 中,Match 用于指向“GET”“POST”以及其他类型请求的操作。

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 GETand POSTin Rails 4?

现在这将指向用户控制器对 GET 和 POST 请求的帐户操作。由于在Rails 4 中“匹配”已被弃用,我们可以在 Rails 4 中为GETPOST创建相同的路由吗?

回答by Tim Dorr

From the matchdocumentation, you can use matchas long as you have via:

match文档中match只要您有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_pathor user_account_urlin this case.

编辑:添加了一个as:参数,以便可以通过 url 帮助程序访问它。user_account_path或者user_account_url在这种情况下。

回答by Ch Zeeshan

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

在路由上, match 方法将不再作为一个包罗万象的选项。您现在应该使用选项指定要响应的 HTTP 动词 :via

Rails 3.2

导轨 3.2

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

Rails 4.0

导轨 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 兼容性的另一个选择是仅使用显式 get、post 或任何其他 HTTP 动词指定您的操作。使用此选项,您仍然可以在今天运行您的代码,并在未来进行升级。

Rails 3.2 and 4.0 compatible

Rails 3.2 和 4.0 兼容

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

multiple verbs

多个动词

get "/users" => "users#index"
post "/users" => "users#index"