0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【エラー解決方法(Rails API)】 406 Not Acceptable,...is missing a template for this request format and variant

Posted at

概要

Rails7とReactでjbuilderを使用して値を返した際に出力された406エラーを解決するための記事です。

エラー内容

api_1    | Completed 406 Not Acceptable in 24ms (ActiveRecord: 5.6ms | Allocations: 1086)
api_1    | 
api_1    | 
api_1    |   
api_1    | ActionController::UnknownFormat (Api::V1::PostsController#index is missing a template for this request format and variant.
api_1    | 
api_1    | request.formats: ["text/html"]
api_1    | request.variant: []):
api_1    |

ソースコード

posts_controller.rb
module Api
  module V1
    class PostsController < ApplicationController
      def index
        @posts = Post.all.order(created_at: 'DESC')
      end
    end
  end
end
app/views/api/v1/posts/index.json.jbuilder
json.set! :posts do
  json.array! @posts do |post|
    json.extract! post,:user, :id, :user_id, :text, :title, :image, :created_at
    post.current_user = current_api_v1_user
    json.favorited_by post.favorited_by?
  end
end
routes.rb
  namespace :api do
    namespace :v1 do
      resources :posts, only: %i[index create edit update destroy] do
        resources  :favorites, only: %i[index create destroy]
      end
    end
  end

解決方法

routes.rbにformat: 'json'の指定をすると解決しました。

routes.rb
  namespace :api, format: 'json' do
    namespace :v1 do
      resources :posts, only: %i[index create edit update destroy] do
        resources  :favorites, only: %i[index create destroy]
      end
    end
  end

指定しないと、レスポンスがjson形式で返されず406エラーになったものと思われます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?