0
0

【Rails】APIにAlbaを導入する方法

Last updated at Posted at 2023-11-01

Albaについて

AlbaはJSONシリアライザーです。

導入方法

以下の手順でRailsのAPIにAlbaを導入できます。

インストールする

Gemfileに以下のように記述してbundle installを実行してインストールします。

gem 'alba'
bundle install

設定ファイルを作成する

config/initializer/alba.rbを以下の内容で作成します。

config/initializer/alba.rb
Alba.backend = :active_support

resourcesディレクトリを作成する

app/resourcesディレクトリを作成し、user_resource.rbを作成します。

app/resources/user_resource.rb
class UserResource
  include Alba::Resource
  
  root_key :user

  attributes :id, :name
end

コントローラーを編集する

コントローラーを以下のように編集します。

app/controllers/api/v1/users_controller.rb
module Api
  module V1
    class UsersController < ApplicationController
      def show
        user = User.find(params[:id])
        render json: UserResource.new(user), status: :ok
      end
    end
  end
end

リクエストする

GET api/v1/users/1をすると以下のようなレスポンスが返ります。

{
  user: {
    id: '1',
    name: 'sample',
  }
}

公式ドキュメント

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