Ruby on Rails:如何仅检索POST和PATCH参数

时间:2016-06-22 08:20:40

标签: ruby-on-rails http post httprequest

所以我想仅在数据是POST或PATCH请求时对数据进行一些修改。在这个问题(Ruby on Rails 3: How to retrieve POST and GET params separatly?)中,有一种方法可以获得POST和GET参数,但是我已经搜索过,而且似乎没有办法只获取PATCH数据。

2 个答案:

答案 0 :(得分:2)

ActionDispatch::Request有许多方法可以检查HTTP动词,其中包括:get?post?patch?put?

所以以下应该可以解决问题:

def some_action
  request.patch? # only patch requests
  # or
  request.request_method == :patch
  # and if you are intrested in both PATCH and POST... combine them!
  request.patch? || request.post?
end 

请注意,您可能有兴趣在路由定义中限制使用的HTTP谓词。使用特定谓词定义您的操作会限制不处理使用相同谓词的请求:

# routes.rb
put '/orders/:id/refuse' => 'orders#refuse'
# so your refuse method accepts only PUT requests

答案 1 :(得分:1)

我相信这会解决问题:

# in some controller's method

if request.patch? || request.post?
  # do your work here
end