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

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

    This works for me:

    In routers.db

    Rails.application.routes.draw do
      post '/posts', to: 'posts#create'
      get '/posts', to: 'posts#list_all'
    end
    

    In posts_controler.rb

    class PostsController < ApplicationController
        def create
            new_post = Post.create( content: params[:content], user_id: params[:user_id] )
            render json: { post: new_post }
        end
    
        def list_all
            request = Post.all
            render json: { all_posts: request }
        end
    end
    

    So each action is referred to one different function

提交回复
热议问题