6
5

More than 3 years have passed since last update.

【Rails6 × React】ActiveStorageで画像のURLを取得し、フロントエンドで表示するまで

Posted at

結論

以下のように実装

avatar_path = Rails.application.routes.url_helpers.rails_representation_url(@user.avatar.variant({}), only_path: true) 

@user.avatarの部分はモデル名、ファイル名(has_one_attached以下の部分)

これって何?

ActiveStorageを導入すると使用できるルーティング。

rails_blob_representation GET    /rails/active_storage/representations/:signed_blob_id/:variation_key/*filename(.:format) active_storage/representations#show

こんなルーティングがActiveStorageを導入すると設定される。ここにアクセスしている。

何が便利なの?

ReactとかRailsアプリの外部からActiveStorageにアクセスする際に必要

avatar_path = Rails.application.routes.url_helpers.rails_representation_url(@user.avatar.variant({}), only_path: true) 
render json: {user: @user, books: @user.books, avatar: avatar_path}

こんな感じでRailsアプリからレスポンスを返して

this.setState({
  user: response.data.user,
  books: response.data.books,
  avatar: response.data.avatar
})

このようにレスポンスを受け取ると、this.state.avatarでアバター画像が扱える。

そして

<img src={this.state.avatar}/>

このようにアバター画像を表示できる。

参考

Railsガイド
https://railsguides.jp/active_storage_overview.html#%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E3%81%AB%E3%83%AA%E3%83%B3%E3%82%AF%E3%81%99%E3%82%8B

6
5
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
6
5