Rails 7.1 extends audio_tag and video_tag to accept Active Storage attachments

ActiveStorage provides an easier way to upload and store the files on various cloud services.

Rails also provides easy way to embed them using the appropriate tags. For example,

  • image_tag
  • audio_tag
  • video_tag

In this article we will see how to embed the ActiveStorage files and what’s changed in the latest update.

Let’s take an example of a Movie model. Our Movie model has various attributes title, duration, etc. The model also has several attachments poster, title_song and trailer

class Movie < ApplicationRecord
  has_one_attached :poster      # Image
  has_one_attached :title_song  # Audio
  has_one_attached :trailer     # Video
end

Before

Before 7.1, we could pass activestorage attachment to the image_tag while embedding the image. Whereas, the same for audio_tag and video_tag was not possible.

The only way to embed the activestorage attachment with audio_tag and video_tag was:

<!-- 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>

The above will result in:

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

After

After Rails 7 extends audio_tag and video_tag to accept Active Storage attachments we don’t need to use polymorphic_path anymore.

Let’s take a look at the same code after this change.

<!-- 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>

The above will result in:

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

Need help on your Ruby on Rails or React project?

Join Our Newsletter