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

前端 未结 6 1506
日久生厌
日久生厌 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:02

    I would say, the best way is to create separate actions in the controller and state them in routes.

    # config/routes.rb
    ...
    get '/my_action' => 'my#my_action_get'
    post '/my_action' => 'my#my_action_post'
    ...
    
    # app/controllers/my_controller.rb
    ...
    def my_action_get
      # do stuff like listing smth
    end
    
    def my_action_post
      # do other stuff
    end
    

    In fact, the same logic is used by Rails by default: index and create actions are both called by requests sent to the same paths (e.g. /articles), however, they have different request methods: GET /articles request is redirected to the index action and lists all articles, and POST /articles is redirected to the create action and creates a new article.

提交回复
热议问题