[Rails-API] 記事詳細API作成

学習記録

はじめに

記事の詳細を返すapiを作成します。

シリアライザ作成

> rails g serializer User name email

シリアライザ確認

class UserSerializer
  include FastJsonapi::ObjectSerializer
  
  attributes :name, :email
  
  # アソシエーションの設定に合わせて追記
  has_many :articles
end

ルーティング設定

Rails.application.routes.draw do
  namespace :api, format: 'json' do
    namespace :v1 do
      resources :articles, only: %i[index show]
    end
  end
end

コントローラ追記

module Api
  module V1
    class ArticlesController < BaseController
      before_action :set_article, only: :show

      ~~~~~~ 省略 ~~~~~~

      def show
        options = { include: %i[user 'user.name' 'user.email'] }
        json_string = ArticleSerializer.new(@article, options).serialized_json

        render json: json_string
      end

      private

      def set_article
        @article = Article.find(params[:id])
      end
    end
  end
end

postmanで確認

JSON形式でしっかりデータが返ってきています。

Image from Gyazo

コメント

タイトルとURLをコピーしました