Rails: Restrict API requests to JSON format

后端 未结 3 734
醉酒成梦
醉酒成梦 2021-02-03 23:31

I would like to restrict requests to all API controllers to being redirected to the JSON path. I would like to use a redirect since also the URL should change according to the r

3条回答
  •  你的背包
    2021-02-04 00:19

    If you want to return a 404, or raise a RouteNotFound error if the format is not :json, I would add a route constraint like this:

    Require JSON format:

    # routes.rb
    MyApp::Application.routes.draw do
      namespace :api, constraints: { format: 'json' } do
        namespace :v1 do
          resources :posts
        end
      end
    end
    

    More information can be found here: http://edgeguides.rubyonrails.org/routing.html#request-based-constraints

提交回复
热议问题