简体   繁体   English

Rails - 从命名路由中提取HTTP谓词

[英]Rails - Extract HTTP Verb From Named Route

Is there a way in Rails to extract the HTTP verb(s) associated with a route? Rails中有一种方法可以提取与路由关联的HTTP谓词吗? For example, given a route like this: 例如,给定这样的路线:

match 'users', to: 'users#show', via: [:get, :post]

Can I achieve something like this? 我能实现这样的目标吗?

users_path.respond_to?(:get) (obviously #respond_to is not the right method) users_path.respond_to?(:get) (显然#respond_to不是正确的方法)

The closest I've managed to come is by doing the following, but it doesn't really seem satisfactory. 我最接近的是通过以下方式来做,但它似乎并不令人满意。

Rails.application.routes.routes.named_routes["users"].constraints[:request_method] # => /^GET$/

For context, I have an action that sets a cookie and then does a redirect_to :back , but this action is available globally across the entire site (it's in the footer). 对于上下文,我有一个动作设置一个cookie然后执行redirect_to :back ,但是这个动作在整个站点全局可用(它在页脚中)。 So, if a user happens to be in a flow, and one of those routes only accepts POSTs, the redirect fails because the request issued is a GET. 因此,如果用户碰巧在流中,并且其中一条路由只接受POST,则重定向失败,因为发出的请求是GET。

The request object is available to your controller. request对象可供您的控制器使用。 The following methods are available to determine the type of HTTP request: 以下方法可用于确定HTTP请求的类型:

if request.get?
  # request is a GET request
if request.post?
  # request is a POST request

There are similar methods for other HTTP request verbs, including PUT and DELETE. 其他HTTP请求动词有类似的方法,包括PUT和DELETE。

UPDATE : 更新

Per the update to the question, the following code can be implemented within your controller to yield the constrained verbs on any named route as a pipe-delimited string: 根据问题的更新,可以在控制器中实现以下代码,以将任何命名路由上的约束动词作为管道分隔的字符串:

Rails.application.routes.named_routes["users"].verb
#=> "GET|POST" 

Accordingly, you can split the string to retrieve an array of each of the HTTP methods specified in the route's constraints : 因此,您可以拆分字符串以检索路径constraints指定的每个HTTP方法的数组:

methods_string = Rails.application.routes.named_routes["users"].verb
#=> "GET|POST"

methods_array = methods_string.split('|')
#=> ["GET", "POST"]

methods_array[0]
#=> "GET"
methods_array[1]
#=> "POST"

for someone looking with it in future you can use 对于将来使用它的人来说,你可以使用

env["REQUEST_METHOD"]

to get HTTP verb of specific action 获取特定操作的HTTP动词

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM