How can I get content type from an ActiveStorage attachment?

Viewed 5565

I'm creating a view that features a video stored via ActiveStorage. Currently I'm displaying the video like this:

%video{ controls: true, preload:"metadata" }
    %source{ src: rails_blob_path(@video.source), type: "TODO: Content Type" }

I'd like to find a way to get the content type from the attachment. I've found that I can get to it by using @video.source.attachment.blob.content_typebut that seems so clunky. Is there another simpler way to go about it that resembles video.source.content_type? Unfortunately using the video_tag helper is not a viable solution for me.

3 Answers

Yes, there is a shorter solution: @video.source_blob.content_type.

I recommend you to look at the source code of ActiveStorage, there you can see all the available methods and possibilities that are not always well documented.

You can access content type directly from the attachment , there is not need to call it in thet blob , just do : @video.content_type

class ActiveStorage::Attachment < ActiveRecord::Base
  self.table_name = "active_storage_attachments"

  belongs_to :record, polymorphic: true, touch: true
  belongs_to :blob, class_name: "ActiveStorage::Blob"

  delegate_missing_to :blob #This line allow you to call all the blob methods from attachmen
Related