【问题标题】:Ruby on Rails : How to retrieve POST and PATCH params onlyRuby on Rails:如何仅检索 POST 和 PATCH 参数
【发布时间】:2016-06-22 08:20:39
【问题描述】:

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

【问题讨论】:

    标签: ruby-on-rails http post httprequest


    【解决方案1】:

    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
    

    【讨论】:

      【解决方案2】:

      我相信这会成功:

      # in some controller's method
      
      if request.patch? || request.post?
        # do your work here
      end
      

      【讨论】:

      • 因此,如果我访问 if 语句中的 params 对象,可以保证它只有来自 PATCH 或 POST 的数据,而没有 GET 数据?
      • @user2968505 非常好。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-14
      • 2011-08-04
      • 1970-01-01
      • 1970-01-01
      • 2017-04-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多