- Ruby / Rails関連
 
Rails 7: audio_tagとvideo_tagヘルパーにActive Storage添付ファイルを指定可能になる(翻訳)
Rails 7: Rails 7: audio_tagとvideo_tagヘルパーにActive Storage添付ファイルを指定可能になる(翻訳)
Active Storageは、さまざまなクラウドサービスにファイルを手軽にアップロードして保存する方法を提供します。
Railsは、以下のような適切なタグを用いてこれらのファイルをビューに埋め込む方法も提供しています。
本記事では、Active Storageファイルを埋め込む方法と、最新アップデートの変更点について解説します。
Movieモデルを例に取ります。このMovieモデルにはtitleやdurationなどさまざまな属性があり、posterやtitle_songやtrailerも添付ファイルとして持っているとします。
class Movie < ApplicationRecord
  has_one_attached :poster      # 画像
  has_one_attached :title_song  # 音声
  has_one_attached :trailer     # 動画
end
改修前
Rails 7.1以前は、画像を埋め込むときにimage_tagにActive Storageの添付ファイルを渡せますが、audio_tagやvideo_tagでは同じことができませんでした。
 audio_tagやvideo_tagにActive Storageの添付ファイルを渡すには、以下のようにpolymorphic_pathを使う方法しかありませんでした。
<!-- Rails 7.1より前 -->
<p>
  <strong>Poster:</strong>
  <%= image_tag(movie.poster) %>
</p>
<p>
  <strong>Title song:</strong>
  <%= audio_tag(polymorphic_path(movie.title_song), controls: true) %>
</p>
<p>
  <strong>Trailer:</strong>
  <%= video_tag(polymorphic_path(movie.trailer), controls: true) %>
</p>
上によって以下のHTMLが生成されます。
<p>
  <strong>Poster:</strong>
  <img src="http://localhost:3000/rails/active_storage/blobs/redirect/eyJxxxx--d02xx77/poster.png">
</p>
<p>
  <strong>Title song:</strong>
  <audio controls="controls" src="/rails/active_storage/blobs/redirect/eyJxxxx--173xxec/title_song.mp3"></audio>
</p>
<p>
  <strong>Trailer:</strong>
  <video controls="controls" src="/rails/active_storage/blobs/redirect/eyJxxxx--ea7xx4f/trailer.mp4"></video>
</p>
改修後
Rails 7のaudio_tagとvideo_tagヘルパーが拡張されてActive Storageの添付ファイルを受け取れるようになり(#44085)、polymorphic_pathが不要になりました(#44085)。
同じコードを変更したものを見てみましょう。
<!-- Rails 7.1以降 -->
<p>
  <strong>Poster:</strong>
  <%= image_tag(movie.poster) %>
</p>
<p>
  <strong>Title song:</strong>
  <%= audio_tag(movie.title_song, controls: true) %>
</p>
<p>
  <strong>Trailer:</strong>
  <%= video_tag(movie.trailer, controls: true) %>
</p>
上によって以下のHTMLが生成されます。
<p>
  <strong>Poster:</strong>
  <img src="http://localhost:3000/rails/active_storage/blobs/redirect/eyJxxxx--69axxb9/poster.png">
</p>
<p>
  <strong>Title song:</strong>
  <audio controls="controls" src="http://localhost:3000/rails/active_storage/blobs/redirect/eyJxxxx--e33xx72/title_song.mp3"></audio>
</p>
<p>
  <strong>Trailer:</strong>
  <video controls="controls" src="http://localhost:3000/rails/active_storage/blobs/redirect/eyJxxxx--f31xx12/trailer.mp4"></video>
</p>
      
概要
元サイトの許諾を得て翻訳・公開いたします。
#44085は、現時点ではmainブランチにのみマージされています。