LoginSignup
2
0

【Rails】レスポンスに画像のパスを追加する方法【ActiveStorage】

Posted at

モデルにメソッドを定義

モデルに画像のパスを取得するためのメソッドを定義します。

user.rb
class User < ApplicationRecord
  has_one_attached :avatar

  def avatar_path
    return unless avatar.attached?

    Rails.application.routes.url_helpers.rails_blob_path(avatar, only_path: true)
  end
end

レスポンスに追加する

以下のように記述することでレスポンスに画像のパスを追加できます。

users_controller.rb
module Api
  module V1
    class UsersController < ApplicationController

      def show
        user = User.find(params[:id])
        # methods: にモデルに定義したメソッドを記述する
        render json: user, methods: [:avatar_path], status: :ok
      end

    end
  end
end 


2
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
2
0