How to handle multiple HTTP methods in the same Rails controller action

前端 未结 6 1421
日久生厌
日久生厌 2021-01-31 02:50

Let\'s say I want to support both GET and POST methods on the same URL. How would I go about handling that in a rails controller action?

6条回答
  •  鱼传尺愫
    2021-01-31 03:10

    Here's another way. I included example code for responding with 405 for unsupported methods and showing supported methods when the OPTIONS method is used on the URL.

    In app/controllers/foo/bar_controller.rb

    before_action :verify_request_type
    
    def my_action
      case request.method_symbol
      when :get
        ...
      when :post
        ...
      when :patch
        ...
      when :options
        # Header will contain a comma-separated list of methods that are supported for the resource.
        headers['Access-Control-Allow-Methods'] = allowed_methods.map { |sym| sym.to_s.upcase }.join(', ')
        head :ok
      end
    end
    
    private
    
    def verify_request_type
      unless allowed_methods.include?(request.method_symbol)
        head :method_not_allowed # 405
      end
    end
    
    def allowed_methods
      %i(get post patch options)
    end
    

    In config/routes.rb

    match '/foo/bar', to: 'foo/bar#my_action', via: :all
    

提交回复
热议问题